mongodb - 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
吗?
解决方案
您可以使用 Mongo 的查询嵌入文档数组。
在您的情况下,它看起来像:
PostSchema.statics.postsOpenedByUser = function (userId, cb) {
return this.find( { "lastOpens.userId" : userId }, cb );
}
这将返回所有包含 userId 的帖子lastOpens
推荐阅读
- c# - 使用 linq 从 C# 列表中的每一行中获取第 n 个单词
- python - 多个熊猫数据框列的重叠密度图
- r - 使用 Python 或 R 从 Postman 中提取数据
- angularjs - 嵌套(第一个)自定义指令另一个(第二个)指令将(第一个)自定义指令移动到子作用域而不是作用域
- c# - 如何使用 Castle Windsor 的基本接口注册服务工厂模式
- c# - 以定时间隔开始/停止在 UDP 端口上接收数据
- r - 计算R中数据帧中ID的出现次数
- reactjs - 如何使用它的snake_case名称动态加载图标(React,material-ui)
- python - 如何在此配置中使用外部 python 包
- python - Python:将 csv 文件的内容添加到列表中