'Mongoose projection to filter list not working, but native does
I'm trying to use the following find query to find a list of objects which are related to a "work" object with a specific ID, then return all "form" elements which aren't set to inactive (active = false).
This works perfectly using the mongo shell locally, or testing on mongoplayground. But I can't figure out how to get mongoose to play nice and return the results I expect, I always get an empty array.
I don't understand why it would work perfectly find natively, but not via mongoose. There must be some kind of issue or peculiarity I'm not finding in the docs. My mongodb version is 5.0.5 and my mongoose version is 6.1.5.
Mongo find query I'm trying to use:
db.objects.find({
"work": ObjectId("61d50a22eed3f421dc33a220")
},
{
"form": {
"$filter": {
"input": "$form",
"as": "form",
"cond": {
"$ne": [
"$$form.active",
false
]
}
}
}
})
Mongoose code with Projection (not working, returning []):
export const getWIObjects = async (workID: string) => {
const objs = await ObjectModel.find({
work: new mongoose.Types.ObjectId(workID),
}).select({
form: {
$filter: {
input: "$form",
as: "form",
cond: {
$ne: ["$$form.active", false],
},
},
},
});
return objs;
};
Mongoose code WITHOUT projection (returning data, but will include inactive fields):
export const getWIObjects = async (workID: string) => {
const objs = await ObjectModel.find({
work: new mongoose.Types.ObjectId(workID),
});
return objs;
};
Solution 1:[1]
What you have written in the Mongoose code with Projection is actually returning documents.
I think why you are getting an empty array [], because you are probably querying an invalid workID that is not in the collection.
Please check the workID you are querying in the find method.
Solution 2:[2]
try using aggregation for this
const objs = await ObjectModel.aggregate([
{
'$match': {
work: mongoose.Types.ObjectId(workID),
"form.active": false
}
}, {
'$project': {
form: {
$filter: {
input: "$form",
as: "f",
cond: {
$ne: ["$$f.active", false],
},
},
},
}
}
])
include form.active key in match also as it will lessen the number of documents after match query only
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pramisha C P |
| Solution 2 | Smriti Shikha |

