【问题标题】:How I can make an query with mongoose from a function using a parameter?如何使用参数从函数中使用猫鼬进行查询?
【发布时间】:2016-04-07 08:02:15
【问题描述】:

我尝试使用这样的函数进行猫鼬查询:

    /*
     * @param {function} Model - Mongoose Model
     * @param {String} searchText- Text that will be used to search for Regexp
     * @param {String} Key- key to search into a Model
     * @param {object} res - Response of node.js / express
    */

function _partialSearch (Model, searchText, key, res) {
  var search = new RegExp(searchText, "i");

  Model.find({ key : { $regex : search } })
  .exec(function (err, docs) {
    if(err) log(err);
    else {
      res.json(docs);
    }
  })
}

我的问题是查询采用参数键文字并像这样搜索:

我需要这个:

_partialSearch(Products, 'banana', 'fruts', res)

我猜到了:

   Products.find({ 'fruts' : 'banana})

但我明白了:

Products.find({ key : 'banana})

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    你不能像那样直接使用变量作为对象键,但假设你使用的是 Node.js 4.0 或更高版本,你可以使用它对computed property names 的 ES6 支持,通过将key 包围在括号:

    Model.find({ [key] : { $regex : search } })
    

    【讨论】:

      【解决方案2】:

      使用 bracket notation 动态创建查询对象,因此您可以按如下方式重构您的函数:

      function _partialSearch (Model, searchText, key, res) {
          var search = new RegExp(searchText, "i"),
              query = {};
          query[key] = { $regex : search };
      
          Model.find(query)
               .exec(function (err, docs) {
                  if(err) log(err);
                  else {
                      res.json(docs);
                  }
               });
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-16
        • 1970-01-01
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        • 2019-01-24
        • 2018-05-26
        • 2020-06-29
        • 1970-01-01
        相关资源
        最近更新 更多