MongoDB中的复杂搜索



我定义了一个PostSchema如下。post是由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  
}

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

谁能帮忙?

编辑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里面做不到的吗?

您可以使用Mongo的查询来获取嵌入的文档数组。

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

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

这将返回lastOpens中具有 userId 的所有帖子

最新更新