[英]Mongoose : find document with subdocument filter
I have an User like so the id
is NOT the _id
)我有一个像这样的用户,所以
id
不是_id
)
{
id: string;
}
Which can create files like so哪个可以像这样创建文件
{
name: string;
author: User;
}
I would like to get all Files
where the author is a given User
, but I do not know how to use the "filter" function to do that.我想获取作者是给定
User
的所有Files
,但我不知道如何使用“过滤器”function 来做到这一点。
So currently I do所以目前我做
const author = await this.userModel.find({ id });
return this.filesModel.find({ author });
Is there a more efficient way to do it?有没有更有效的方法来做到这一点?
(I use NestJS with the Mongoose integration, the syntax used is the same as the Mongoose library) (我使用带有 ZCCADCDEDB567ABAE643E15DCF0974E503Z 集成的 NestJS,使用的语法与 Mongoose 库相同)
EDIT编辑
Given the User
document给定
User
文档
{
_id: 'OVZVIbovibiugb44'
id: 10
}
And the Files
documents和
Files
文件
[
{ name: "1.docx", author: ObjectId('OVZVIbovibiugb44') },
{ name: "2.docx", author: ObjectId('voisbvOVISBEIVBv') },
]
I would like to use the function我想使用 function
findOwned(authorId = 10) {
const author = await this.userModel.find({ id });
return this.filesModel.find({ author });
// But do it only with "filesModel"
}
And get, as a result,结果,得到,
[
{ name: '1.docx', author: 'ObjectId('OVZVIbovibiugb44') },
]
You can use $lookup
into an aggregation
query to merge collections.您可以在
aggregation
查询中使用$lookup
来合并 collections。
Also, as your id
is an String and your author
is an ObjectId
you will need one previous stage using $toObjectId
此外,由于您的
id
是一个字符串,而您的author
是一个ObjectId
,您将需要使用$toObjectId
的前一个阶段
So the query is similar to this:所以查询类似于:
$match
stage (optional) to query only with documents you want. $match
阶段(可选)仅查询您想要的文档。 Like a filter$project
to convert id
String field to ObjectId
. $project
将id
String 字段转换为ObjectId
。 You can user $set
also.$set
。$lookup
to merge collection and the ouput is in a field called files
. $lookup
合并集合,输出位于名为files
的字段中。$project
to output only files
array from the merge. $project
到 output 仅来自合并的files
数组。db.User.aggregate([
{ "$match": { "id": "5a934e000102030405000001" } },
{ "$project": { "id": { "$toObjectId": "$id" } } },
{ "$lookup": {
"from": "Files",
"localField": "id",
"foreignField": "author",
"as": "files" }
},
{ "$project": { "files": 1 } }
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.