Find using _id not working with aggregation [duplicate]
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: []
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 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] }
]
}
}
}
}}
])