How I can make an query with mongoose from a function using a parameter?

前端 未结 2 1968
暖寄归人
暖寄归人 2021-01-28 05:16

I try make a mongoose query using a function like this:

    /*
     * @param {function} Model - Mongoose Model
     * @param {String} searchText- Text that will          


        
相关标签:
2条回答
  • 2021-01-28 05:46

    Use the bracket notation to create the query object dynamically, so you could restructure your function as follows:

    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);
                }
             });
    }
    
    0 讨论(0)
  • 2021-01-28 05:55

    You can't directly use a variable as an object key like that, but assuming you're using Node.js 4.0 or above, you can use its ES6 support for computed property names to do this by surrounding key in brackets:

    Model.find({ [key] : { $regex : search } })
    
    0 讨论(0)
提交回复
热议问题