node.js - Mongoose: Sort by latest Comment.creationDate in comments array of a forum post -
i have following object
let threadschema = mongoose.schema({ author: { type: mongoose.schema.types.objectid, required: true, ref: 'user' }, title: { type: string, required: true }, content: { type: string, required: true }, id: { type: number, required: true, unique: true }, answers: [{ type: mongoose.schema.types.objectid, default: [], ref: 'answer' }] })
like can see, array of answer objects:
let answerschema = mongoose.schema({ thread: { type: mongoose.schema.types.objectid, // article required: true, ref: 'thread' }, author: { type: mongoose.schema.types.objectid, // user required: true, ref: 'user' }, creationdate: { type: date, required: true }, content: { type: string, required: true } })
and want is, in mongoose query db, sort threads ones latest (newest) answers in them.
i tried stupid as:
thread .find() .populate('answers') .sort('answers.creationdate') .then((threads) => { console.log(threads) })
but no luck that. can proper expertise guide me in right way , tell me if i'm trying @ possible? in advance :)
try putting sort in populate step if sort answers subdocument array inside thread
thread .find() .populate({ path: 'answers', options: { sort: { 'creationdate': : -1 } } }) .then((threads) => { console.log(threads) })
Comments
Post a Comment