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;
};
I tried the following with MongoDB v5.0.6 and Mongoose v6.2.4, and the query returns results with the expected projection.
const projectn =
{
form: {
$filter: {
input: "$form",
as: "f",
cond: {
$ne: [ "$$f.active", false ]
}
}
}
};
const filter = { }; // substitute your filter
const result = await MyModel.find(filter, projectn);
The following query (with different syntax) also returned the same result.
const result = await MyModel.find(filter).select(projectn);
NOTE: This projection syntax using aggregation operators requires at least MongoDB v4.4.