C
C
CartmanGui2016-04-01 17:12:27
MongoDB
CartmanGui, 2016-04-01 17:12:27

How to sort by array object field?

There is a topic model with messages

var schemaMessage = new Schema({
    message: {
        type: String,
        required: true
    },
    from: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    to: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    date_created: {
        type: Date,
        default: Date.now
    }});

var schemaTopic  = new Schema({
    title: {
        type: String,
        required: true
    }
    ,messages: [schemaMessage]   
    ,date_created: {
        type: Date,
        default: Date.now
    }
});

It is necessary to display to the user a list of topics sorted by the date of the last message in them for him

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lega, 2016-04-02
@lega

list of topics sorted by the date of the last message in them for him

To do this, you need to store the date of the last message in the topic.
In theory, such a query can be made on the AgregationFramework, but it will not use indexes, which means there will be a full pass through the collection, which means it will slow down when the base grows.
Even if you were using SQL, such a column would be desirable, and necessary in the worst case.

C
CartmanGui, 2016-04-02
@CartmanGui

To do this, in the topic you need to store the date of the last message.
The matter is that it is necessary for each user to sort topics by the message for it, and in your case sorting will be simple on the last message it is not important for whom.
Until I came to a conversational decision
schema.statics.getTopicList = function (userId, offset, callback) {
    var Topic = this;
        ,q = [
        {$unwind: "$messages"},
        {$match: {$or: [{"messages.to": userId}, {"messages.from": userId}]}},
        {$sort: {"messages.date_created": -1}},
        {$group: {
                    _id: "$_id",
                    "title":{$first: "$title"},
                    "date_last_message":{$first: "$messages.date_created"},
                    "date_created":{$first: "$date_created"},
                }
        },
        {$sort: {"date_last_message": -1}},
    ];
    if(offset != undefined) {
        q.push({$skip: (config.get('topic:limit') * offset)});
        q.push({$limit: config.get('topic:limit')});
    }

    this.aggregate(q,function(err, topics) {
        if(err) return callback(err);
        callback(null,topics);
    });

};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question