MongoDB管道查询

huangapple go评论77阅读模式
英文:

MongoDB pipeline Query

问题

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

英文:

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

答案1

得分: 1

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

我假设你关心的是NoSQL注入。查看mongo-sanitize

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

或者使用

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

英文:

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}
    }},
    ....,
]

huangapple
  • 本文由 发表于 2023年7月18日 07:16:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定