node.js - 如何在node js中获取表单数据并查询mongodb

标签 node.js mongodb

我正在尝试获取表单数据,查询数据库并查找与该数据相关的文档数量,并控制台计数(为了简单起见)。

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/

相关文章:

javascript - NPM、Supervisor 和 Nohup 在 shell session 之间退出

javascript - 为什么 Mongoose 错误对象中没有消息?

python - 如何聚合两个集合,其中一个集合的字段大于另一个集合

mongodb - 如何知道mongodb使用的是哪个存储引擎?

MongoDb 聚合匹配日期部分

json - 在python中将pymongo查询集序列化为json

javascript - 使用history.push时如何重定向到另一个端口?

node.js - "Segmentation Fault": when using xlsx npm module in node. linode 上的 js 应用程序

javascript - Chai Sinon,should.have.been 标志未定义?

mongodb - 带有副本集的 Mongo 容器,在 docker-compose 中只有一个节点