Answer the question
In order to leave comments, you need to log in
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
}
});
Answer the question
In order to leave comments, you need to log in
list of topics sorted by the date of the last message in them for him
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 decisionschema.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 questionAsk a Question
731 491 924 answers to any question