Mongoose ODM: how to get the first and last five elements from an array of embedded documents?

I am writing a simple forum with NodeJS / Express / MongoDB, and I have a little problem with Mongoose ODM for Mongo.

I have boards, threads, and mail models like these (slightly 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'}, }); 

Thus, messages are embedded in streaming documents. I want to display a list of threads with some messages: the first and last five . Is it possible to achieve this in a single request? I can get the first OR last five using the slice function, but I need something more elegant than two almost identical queries. Here is my current request:

 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); }); 
+4
source share

Source: https://habr.com/ru/post/1500457/


All Articles