本文介绍了如何使用参数从函数中使用mongoose进行查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用这样的函数做一个mongoose查询:
I try make a mongoose query using a function like this:
/*
* @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);
}
})
}
我的问题是查询采取参数键文字和搜索,如下所示:
My problem is the query take a parameter key literal and search like this:
我需要这样:
_partialSearch(Products, 'banana', 'fruts', res)
我观察:
Products.find({ 'fruts' : 'banana})
但是我得到这个:
Products.find({ key : 'banana})
推荐答案
使用 可动态创建查询对象,因此可以如下重新构建函数:
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);
}
});
}
这篇关于如何使用参数从函数中使用mongoose进行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!