4

我正在用 NodeJS/Express/MongoDB 编写一个简单的论坛引擎,我对 Mongoose ODM for Mongo 有一点问题。

我有类似的板、线和柱模型(有点简化):

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'},
});

因此帖子嵌入在线程文档中。我想显示一些帖子的线程列表:第一个和五个最新的。是否有可能在一个查询中实现这一目标?我可以使用slice函数获得第一个最新的五个,但我想要比两个几乎相同的查询更优雅的东西。这是我当前的查询:

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

0 回答 0