首页 > 解决方案 > MongoDB中的复杂搜索

问题描述

我定义了 aPostSchema如下。A由 apost编写author,并且可以被许多人阅读:lastOpens是 的数组{ time: ... , userId: ... }

var PostSchema = new mongoose.Schema({
    title: { type: String }
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' },
    lastOpens: { type: Array, default: [] }
})

现在,我想编写一个静态方法来返回一个用户阅读的所有帖子:

PostSchema.statics.postsOpenedByUser = function (userId, cb) {
  // need to go through all the posts, and check their `lastOpens`. 
  // If `userId` is in `userId` of a `lastOpen`, then count the post in  
}

我所知道的是find({ ... })MongoDB之类的方法。但我不知道如何指定像我这样更复杂的搜索。

有人可以帮忙吗?

编辑1:我尝试$where按如下方式使用运算符,但它不起作用:

PostSchema.statics.postsOpenedByUser = function (userId, cb) {
    return this.find({ $where: function () {
        var index = -1; 
        for (var i = 0; i < this.lastOpens.length; i++)
            if (this.lastOpens[i].userId === userId) { index = i; break }
        return !(index === -1)
}}, cb)

里面有什么是我们不能做的$where吗?

标签: mongodbmongoose

解决方案


您可以使用 Mongo 的查询嵌入文档数组

在您的情况下,它看起来像:

PostSchema.statics.postsOpenedByUser = function (userId, cb) {
    return this.find( { "lastOpens.userId" : userId }, cb );
}

这将返回所有包含 userId 的帖子lastOpens


推荐阅读