skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Why not simply?

    pipeline = [
        {match: {
          objectId: params.id,
          isDeleted: {$ne : true}
        }},
        ....,
    ]
    

    I assume you are concerned about NoSQL-Injection. Have a look at mongo-sanitize

    var sanitize = require('mongo-sanitize');
    pipeline = [
        {match: {
          objectId: sanitize(params.id),
          isDeleted: {$ne : true}
        }},
        ....,
    ]
    

    or use

    pipeline = [
        {match: {
          objectId: JSON.stringify(params.id),
          isDeleted: {$ne : true}
        }},
        ....,
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search