用Mongoose以编程方式构建动态查询 [英] Programmatically build dynamic query with Mongoose
问题描述
我正在尝试根据从表单接收到的输入来构建搜索.
I'm trying to build a search from input received from a form.
router.get('/data', function(req, res) {
var firstName=req.body.firstName,
lastName=req.body.lastName,
companyName=req.body.companyName,
email=req.body.email;
});
我想根据这些值建立一个查询,但是如果该字段没有值,我显然不想在搜索中包括它(搜索"会改变结果)
I'd like to build a query up from these values, but if the field has no value, I obviously don't want to include it in the search (searching for "" would change the results)
我尝试了几种不同的方法,例如构建一个字符串放置在其中:
I've tried a couple different things, like building a string to place in:
mongoose.model('customers').find({QUERY STRING WOULD GO HERE} ,function(err, data) {
if (err) return console.error(err);
console.log(data);
});
但这似乎无法正常工作.我也尝试过像这样的堆叠"搜索查询:
But that doesn't seem to work properly. I also tried "stacking" search queries like this:
if(firstName !="") {
mongoose.model('customers').find({firstName: firstName})
}
然后执行如下搜索:
mongoose.model('customers').exec(function(err, customer){
console.log(customer);
});
但这会导致500个错误(而且我不确定是否可以从中获取更多信息).
But that causes 500 errors (and I'm not sure if there's any more info I can get from them).
请帮助新手动态建立猫鼬搜索查询:(
Please help a Newbie dynamically build a mongoose search query :(
推荐答案
尝试创建query
对象,例如:
//generate query object based on availability of value
var query = {};
if( your_variable !== "" ) {
query["some_key"] = your_variable;
}
if( your_second_variable !== "" ) {
query["some_other_key"] = your_second_variable;
}
mongoose.model('customers').find(query, function(err, c) {
//do something
});
这篇关于用Mongoose以编程方式构建动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!