Node.js 如何使用node和express从搜索表单查询mongodb
我想制作一个HTML表单来查询MongoDB。如何编写忽略空白字段的逻辑?例如,我有两个搜索参数。如果lastname字段为空,我将如何编写查询以忽略该字段Node.js 如何使用node和express从搜索表单查询mongodb,node.js,express,node-mongodb-native,Node.js,Express,Node Mongodb Native,我想制作一个HTML表单来查询MongoDB。如何编写忽略空白字段的逻辑?例如,我有两个搜索参数。如果lastname字段为空,我将如何编写查询以忽略该字段 router.post('/auth/search', auth, function(req,res){ var db = req.db; console.log(req.body); db.users.find({ 'firstname': req.body.firstname,
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);
});
});
谢谢你的帮助。谢谢 只有当属性是真实的时,才能将它们添加到查询中:
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) {
// …
});
通过动态生成搜索对象
router.post('/auth/search', auth, function(req,res){
var db = req.db;
console.log(req.body);
var obj = {}
if(req.body.firstname) {
obj['firstname'] = req.body.firstname;
}
if(req.body.lastname) {
obj['lastname'] = req.body.lastname;
}
db.users.find(obj, function(err, docs){
if (err) return err;
console.log(docs);
res.send(docs);
});
});
curl-d'$where=function(){while(true);}'
说“不要那样做”。@harpreethingh,这是一个白名单/净化输入的问题。您不想公开信任从最终用户发送的任何参数。哦,是的,这肯定是一个大错误。虽然我知道,但这次我忘了。现在它将被永远记住。谢谢:)