小编Ste*_*ley的帖子

使用Mongoose以编程方式构建动态查询

我正在尝试根据从表单收到的输入构建搜索.

router.get('/data', function(req, res) {
    var firstName=req.body.firstName,
    lastName=req.body.lastName,
    companyName=req.body.companyName,
    email=req.body.email;
});
Run Code Online (Sandbox Code Playgroud)

我想从这些值构建一个查询,但如果该字段没有值,我显然不希望将其包含在搜索中(搜索""会更改结果)

我尝试了几个不同的东西,比如建一个字符串放在:

mongoose.model('customers').find({QUERY STRING WOULD GO HERE} ,function(err, data) {
    if (err) return console.error(err);
    console.log(data);
});
Run Code Online (Sandbox Code Playgroud)

但这似乎不能正常工作.我也试过像这样"堆叠"搜索查询:

if(firstName !="") {
    mongoose.model('customers').find({firstName: firstName})
}
Run Code Online (Sandbox Code Playgroud)

然后像这样执行搜索:

mongoose.model('customers').exec(function(err, customer){
    console.log(customer);
});
Run Code Online (Sandbox Code Playgroud)

但这会导致500个错误(我不确定我是否可以从中获取更多信息).

请帮助新手动态构建一个猫鼬搜索查询:(

mongoose node.js

16
推荐指数
3
解决办法
1万
查看次数

标签 统计

mongoose ×1

node.js ×1