I am trying to build a MongoDB pipeline query but I can’t get it to work. The modified query is below.
pipeline = [
{match: {
objectId: JSON.stringify({$eq : 'params.id'}),
isDeleted: {$ne : true}
}},
....,
]
console.log(pipeline)
When I print this query I get the results below
[ { match: { objectId: '{"$eq":"params.id"}', isDeleted: [Object] } } ]
which fails to execute. The are two problems, the first is JSON.stringify
quotes the entire condition in a single quote after objectId
. The second problem is without JSON.stringify
my conditions are treated as an [Object]
as in isDeleted
.
What I am expecting is
[ { match: { objectId: {$eq:"params.id"}, isDeleted: {$ne : true} } } ]
You can reproduce this by saving the sample code in .js
file and executing it using node file.js
2
Answers
Instead of using the JSON.stringify method, you can directly write the conditions as regular JavaScript objects. Be careful with this however as you may run into code logic issues.
This question lacks more detail to assist further.
Why not simply?
I assume you are concerned about NoSQL-Injection. Have a look at mongo-sanitize
or use