使用 _id 查找不适用于聚合 [英] Find using _id not working with aggregation
本文介绍了使用 _id 查找不适用于聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 mongodb 的初学者,我正在尝试在 node.js 应用程序中使用 mongoose 编写查询:
I'm beginner to mongodb and I'm trying to write a query using mongoose in node.js application:
const objectIdValue = secondId.valueOf();
const existedRelation = await this.model.aggregate([
{ $match: { _id: firstId } },
{ $project: {
relations: {
$filter: {
input: '$links',
as: 'link',
cond: {
$and: [
{ $eq: ['$$link.target.entityId', `${objectIdValue}`] },
{ $eq: ['$$link.linkTypeId', linkTypeId] },
],
},
},
},
},
},
]);
console.log('existedRelation: ', existedRelation);
当我执行它时,我得到了这个结果:
When I execute it I got this result:
existedRelation: []
我尝试使用 mongoShell 执行它:
I tried to execute it using mongoShell:
db.tasks.aggregate([
{ $match:{ _id: ObjectId("5bbf5800be37394f38a9727e") }},
{
$project: {
relations:{
$filter:{
input: '$links',
as: "link",
cond: {
$and: [
{$eq:["$$link.target.entityId", '5bbf52eabe37394f38a97276']},
{$eq: ["$$link.linkTypeId", ObjectId("5bbf4bfcb075e03bd4a1b779")]}
]
}
}
}
}
}
我得到了我想要的结果.我犯了什么错误?
And I got the results that I want. What is the mistake that I made ?
推荐答案
Mongoose 不会在聚合函数中将 String
转换为 ObjectId
.所以你必须使用 mongoose 手动投射它.
Mongoose doesn't cast String
to ObjectId
in aggregate function. So you have to cast it manually using mongoose.
var mongoose = require('mongoose')
const existedRelation = await this.model.aggregate([
{ "$match": { "_id": mongoose.Types.ObjectId(firstId) } },
{ "$project": {
"relations": {
"$filter": {
"input": "$links",
"as": "link",
"cond": {
"$and": [
{ "$eq": ["$$link.target.entityId", `${objectIdValue}`] },
{ "$eq": ["$$link.linkTypeId", linkTypeId] }
]
}
}
}
}}
])
这篇关于使用 _id 查找不适用于聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文