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

Ste*_*ley 16 mongoose node.js

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

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个错误(我不确定我是否可以从中获取更多信息).

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

Sud*_*oti 26

尝试创建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
});
Run Code Online (Sandbox Code Playgroud)


Tom*_*ski 8

对于使用较新JavaScript(尤其是在Node.js 7.6.0+或Babel上)的用户。

我发现以编程方式构建查询(基于if子句等)的最佳方法是使用查询和替代语法。

let query = PersonModel().find();

if (isMale) {
    query.where('sex', 'male'); 
} else {
    query.where('sex', 'female');
}

query.where('alive', true);

// and then to run the query
const result = await query.exec();
Run Code Online (Sandbox Code Playgroud)

请注意async/await此处的用法。它可以在Node.js 7.6.0+上完美运行。如果您不想使用async/await,则可以像下面这样使用Promises:

query.exec().then(result => {
    // result has your... results
});
Run Code Online (Sandbox Code Playgroud)


Tal*_*wan 7

为了避免独立检查每个参数,您可以遍历它们。

var query = {};
for(var key in req.body){ //could also be req.query and req.params
  req.body[key] !== "" ? query[key] = req.body[key] : null;
}

mongoose.model('customers').find(query, function(err, customers){

})
Run Code Online (Sandbox Code Playgroud)