首页 > 解决方案 > 从查询字符串中检索的查询对象中查找 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] } ] }

标签: javascriptexpressmongooseserver-side

解决方案


 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);
    }
  });

推荐阅读