NodeJS Express从字符串创建Mongoose查询



我有这个字符串:

var filter = '{stamps:{$gte: 2020-11-06 06:42:25.000+01:00, $lte: 2020-11-06 09:52:25.000+01:00}'

不知怎么的,我不得不用这个字符串查询mongoDB集合。

Message.find(filter, function(err, messages){
if(err){
console.log(err);
}else{
//do something here
}
})

当然,我得到了这个错误:

ObjectParameterError: Parameter "filter" to find() must be an object, got {stamps:{$gte: 2020-11-06 06:42:25.000+01:00, $lte: 2020-11-06 09:52:25.000+01:00}

有没有办法将这个字符串强制转换为mongoDB可以接受的对象?

您可以更改构建查询的方式,将其作为JSON传递,然后使用JSON.parse()/JSON.stringify()

// Note the necessary double quotes around the keys
const jsonFilter = '{ "stamps": { "$gte": "2020-11-06 06:42:25.000+01:00", "$lte": "2020-11-06 09:52:25.000+01:00" } }'
const query = JSON.parse(jsonFilter)
Message.find(query, callback)

或者您可以引入另一个依赖项,比如mongodb查询解析器,它可以为您解析字符串。

const parser = require('mongodb-query-parser')
// Note it still needs double quotes around the dates to run properly
const filter = '{stamps:{$gte: "2020-11-06 06:42:25.000+01:00", $lte: "2020-11-06 09:52:25.000+01:00" } }'
const query = parser(filter)
Message.find(query, callback)

https://runkit.com/5fbd473b95d0a9001a2359b3/5fbd473b98492c001a8bba06


如果不能在字符串中的值周围包含引号,可以使用正则表达式添加它们。但请记住,这个正则表达式是为匹配这种精确的日期格式而定制的。如果格式可以更改,或者您希望同时匹配其他数据类型,则应尝试从一开始就将它们包含在筛选字符串中。

const parser = require("mongodb-query-parser")
const filter = '{stamps:{$gte: 2020-11-06 06:42:25.000+01:00, $lte: 2020-11-06 09:52:25.000+01:00} }'
const filterWithQuotedDates = filter.replace(/(d{4}-d{2}-d{2} d{2}:d{2}:d{2}.d{3}(+d{2}:d{2})?)/g, '"$1"')
parser(filterWithQuotedDates)
Message.find(query, callback)

https://runkit.com/5fbd494bcd812c0019b491fb/5fbd4951ebe43f001a5b590a


应该注意的是,一个常见的用例是通过URL参数传递MongoDB查询,并且有专门的包:

  • https://github.com/Turistforeningen/node-mongo-querystring
  • https://github.com/fox1t/qs-to-mongo

最新更新