javascript - 从查询字符串中检索的查询对象中查找 Mongoose
问题描述
我从一个 URL 中获取一个查询字符串并解析然后映射它,所以我得到一个像这样的对象:
{ '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] }
这是一个名为 q 的常量。
那么 Mongoose 的 find 查询会是什么样子呢?我试过这个:
Schema.find(q, function (err, results) {
if (err) {
console.log(err);
}
else {
console.log(results);
}
});
但它会返回空列表([])。在控制台记录 q 时,这将打印到控制台:
{ '$and': [ { length: [Object] }, { length: [Object] } ] }
解决方案
const q= { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] }
// converting string key to integer
q['$and'].map(function(obj) {
for(var prop in obj.length){
if(obj.length.hasOwnProperty(prop) && obj.length[prop] !== null && !isNaN(obj.length[prop])){
obj.length[prop] = +obj.length[prop];
}
}
});
console.log(q)
Schema.find(q, function (err, results) {
if (err) {
console.log(err);
}
else {
console.log(results);
}
});
推荐阅读
- c# - 禁用按钮的 C# Paint 事件(WinForms)
- django-unittest - 模拟 python kafka 生产者
- java - 如何使用 ojdbc8_g.jar 启用 JDBC 日志记录的堆栈跟踪
- java - SAP Hybris Commerce - 更改在线和离线目录会导致不同步
- php - 提交按钮不调用控制器功能 - Laravel
- javascript - SVG 箭头动画
- python - Python Bokeh 绘制静态辅助 y 轴
- android - 如何在android中适合Drawable对象的宽度和高度?
- reactjs - 是否可以通过使用 reactjs 给出 rows={3} 来拉伸输入字段
- c++ - 我该如何解决这个问题并调试它,因为我已经匹配了它