Sli*_*lim 6 mongoose mongodb aggregation-framework
我是 mongodb 的初学者,我正在尝试在 node.js 应用程序中使用 mongoose 编写查询:
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);
Run Code Online (Sandbox Code Playgroud)
当我执行它时,我得到了这个结果:
existedRelation: []
Run Code Online (Sandbox Code Playgroud)
我尝试使用 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")]}
]
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了我想要的结果。我犯了什么错误?
Ash*_*shh 10
Mongoose 不会强制String转换ObjectId为聚合函数。所以你必须使用猫鼬手动投射它。
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] }
]
}
}
}
}}
])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2700 次 |
| 最近记录: |