javascript - Mongoose:使用子文档过滤器查找文档
问题描述
我有一个像这样的用户id
不是)_id
{
id: string;
}
哪个可以像这样创建文件
{
name: string;
author: User;
}
我想得到所有Files
给定作者的地方User
,但我不知道如何使用“过滤器”功能来做到这一点。
所以目前我做
const author = await this.userModel.find({ id });
return this.filesModel.find({ author });
有没有更有效的方法来做到这一点?
(我使用 NestJS 与 Mongoose 集成,使用的语法与 Mongoose 库相同)
编辑
鉴于User
文件
{
_id: 'OVZVIbovibiugb44'
id: 10
}
和Files
文件
[
{ name: "1.docx", author: ObjectId('OVZVIbovibiugb44') },
{ name: "2.docx", author: ObjectId('voisbvOVISBEIVBv') },
]
我想使用该功能
findOwned(authorId = 10) {
const author = await this.userModel.find({ id });
return this.filesModel.find({ author });
// But do it only with "filesModel"
}
结果,得到,
[
{ name: '1.docx', author: 'ObjectId('OVZVIbovibiugb44') },
]
解决方案
您可以使用$lookup
intoaggregation
查询来合并集合。
此外,由于您id
是一个字符串,而您author
是一个,ObjectId
您将需要使用前一个阶段$toObjectId
所以查询类似于:
$match
阶段(可选)仅查询您想要的文档。像一个过滤器$project
将id
字符串字段转换为ObjectId
. 你也可以用户$set
。$lookup
合并集合,输出位于名为files
.$project
files
从合并中仅输出数组。
db.User.aggregate([
{ "$match": { "id": "5a934e000102030405000001" } },
{ "$project": { "id": { "$toObjectId": "$id" } } },
{ "$lookup": {
"from": "Files",
"localField": "id",
"foreignField": "author",
"as": "files" }
},
{ "$project": { "files": 1 } }
])
这里的例子
推荐阅读
- reactjs - 在 webpack 构建期间未将 Favicon 添加到构建文件夹
- vba - 选择文件夹(收件箱)并在移动的电子邮件中执行宏
- r - 删除 RStudio 并重新安装后,无法访问站点
- node.js - MongoParseError: URI 没有主机名、域名和 tld
- sql-server - 列出未连接到的实例下的数据库
- python-3.x - 如何使用 IPOPT 在 Pyomo 中指定渐变
- python - 哈希方法在 python 2 中默认,而不是 python 3
- python - PySpark Foreach
- vb.net - 打开远程桌面并连接到计算机
- curl - 使用 J 从安全链接中读取 CSV 文件