node.js - Mongoose ODM: how to get first one and last five elements from array of embedded documents? -
i'm writing simple forum engine nodejs/express/mongodb , have little problem mongoose odm mongo.
i have board, thread , post models (a little bit simplified):
var boardschema = mongoose.schema({ _id: objectid, }); var threadschema = mongoose.schema({ _id: objectid, board: {type: objectid, ref: 'board', index: true}, posts: [postschema], }); var postschema = mongoose.schema({ _id: objectid, thread: {type: objectid, ref: 'thread'}, });
so posts embedded in thread documents. want display list of threads posts: first 1 , 5 latest ones. possible achieve in 1 query? can first or latest 5 using slice function, want more elegant 2 identical queries. here current query:
threadmodel .find( {board: boardid, is_deleted: false}, {posts: {$slice: -5}} ) .sort({last_updated: 1, is_sticky: 1}) .skip(settings.threadsonpage * parseint(pagepointer, 10)) .limit(settings.threadsonpage) .populate('board') .exec(function(err, threads){ if (err) return callback(err); if (threads === []) return callback(404); callback(null, threads); });
Comments
Post a Comment