如何使用节点和expression式从search表单中查询mongodb

我想制作一个HTML表单来查询MongoDB。 我如何编写逻辑来忽略空白字段? 例如,我有两个search参数。 如果姓氏字段为空,我将如何编写查询来忽略该字段?

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) { // … }); 

通过dynamic地创buildsearch对象。

 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); }); });