我正在尝试获取表单数据,查询数据库并查找与该数据相关的文档数量,并控制台计数(为了简单起见)。
app.post('/process_get', function(req, res){
response = {
first_name : req.body.first_name,
last_name : req.body.last_name,
gender: req.body.gender
};
dbConn.then( function (db) {
var dbo = db.db("azima");
var count = dbo.collection('users').find({first_name: req.body.first_name}, {gender: req.body.gender}).count();
console.log(count);
});
console.log(response);
//convert the response in JSON format
res.end('Data received:\n' + JSON.stringify(req.body));
});
但我正在关注:
Example app listening at http://:::8888
{ first_name: 'Najar Man', last_name: 'Malakar', gender: 'Male' }
Promise { <pending> }
我知道这是因为异步性质,但我不知道如何执行这个“简单”操作,因为我是 Node.js 和 mongodb 的新手。
如何正确地将 count
值存储到变量中?
最佳答案
如果您使用的是最新技术。使用异步/等待。
app.post('/process_get',function(req, res){
response = {
first_name : req.body.first_name,
last_name : req.body.last_name,
gender: req.body.gender
};
dbConn.then( function (database) {
var dbo = database.db("azima");
var count
dbo.collection('users').find({first_name: req.body.first_name},
{gender: req.body.gender})
.count(function(err,resCount){
if(err){
console.log(err)}
else{
count = resCount
console.log(count);
res.end('Data received:\n' + JSON.stringify(req.body));
}
});
}).catch(function(e){console.log(e)})
console.log(response);
//convert the response in JSON format
});
尝试添加此内容,如果可以,则可以,否则尝试共享 catch block 中的内容 此外,当您从 mongo 查询发送数据时,您需要将 res.send 放入 dbConn.then 内,否则它将不会等待 mongodb 查询,您将发送
关于node.js - 如何在node js中获取表单数据并查询mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52446524/