gpt4 book ai didi

node.js - 如何使用 node 和 express 从搜索表单中查询 mongodb

转载 作者:搜寻专家 更新时间:2023-10-31 23:54:46 25 4
gpt4 key购买 nike

我想制作一个 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);
});
});

感谢任何帮助。谢谢!

最佳答案

只有当它们为真时,您才能将属性添加到查询中:

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

关于node.js - 如何使用 node 和 express 从搜索表单中查询 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24598302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com