4 node.js express node-mongodb-native
我想制作一个 HTML 表单来查询 MongoDB。如何编写忽略空白字段的逻辑?例如,我有两个搜索参数。如果姓氏字段为空,我将如何编写查询以忽略该字段?
router.post('/auth/search', auth, function(req,res){
var db = req.db;
console.log(req.body);
db.users.find({ 'firstname': req.body.firstname,
'lastname' :req.body.lastname // if this field is blank in the form how can I ignore it?
}, function(err, docs){
if (err) return err;
console.log(docs);
res.send(docs);
});
});
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助。谢谢!
仅当属性为真时,您才可以向查询添加属性:
var query = {};
if (req.body.firstname) {
query.firstname = req.body.firstname;
}
if (req.body.lastname) {
query.lastname = req.body.lastname;
}
db.users.find(query, function (err, docs) {
// …
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7955 次 |
| 最近记录: |