我已经定义了
PostSchema
具体如下。A
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
}
我知道的是
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)
有什么我们不能在里面做的吗
$哪里
?