简体   繁体   English

如何从Node JS中的mongodb查询中获取变量?

[英]How do I get a variable out of a mongodb query in node js?

I want to get a variable out of a mongodb query in node.js which would count the number of documents in a collection named students 我想从node.js中的mongodb查询中获取一个变量,该变量将计算名为students的集合中的文档数

I tried to declare a global variable right before the query and tried to assign the value inside the query function: 我试图在查询之前声明一个全局变量,并尝试在查询函数中分配值:

router.get('/dashboard', loggedin, function (req, res, next) {
// Student is a db object of a collection named students
var std_count

Student.find(function(err, doc) {
  if(err) console.log(err)
  else {
  std_count = doc.length
  }
})

console.log(std_count)

res.render('dashboard', {
  user:req.user
  })
});

The console.log() always prints undefined , but if I put the console.log() inside else{} block, it prints the correct result. console.log()总是打印undefined ,但是如果我将console.log()放在else{}块中,它将打印正确的结果。

I need to do 4 more queries like this (say teachers, courses etc.) and send them altogether in res.render() 我需要再执行4个这样的查询(例如老师,课程等),并将它们一起发送到res.render()

Any help would be appreciated. 任何帮助,将不胜感激。

Mongoose .find returns a promise by chaining .exec to the end, 猫鼬.find通过将.exec链接到最后来返回承诺,

router.get('/dashboard', loggedin, function (req, res, next) {

    // Student is a db object of a collection named students
    Student.find({})
    .exec()
    .then(data => {

        const std_count = data.length;
        res.render('dashboard', {
            user:req.user
        });
    })
    .catch(err => res.status(500));

});

Update: 更新:

Then you can use await each query and send them lastly in the res.render . 然后,您可以使用await每个查询,最后在res.render发送它们。

router.get('/dashboard', loggedin, async function (req, res, next) {
    try {
        const std_count = (await Student.find({}).exec()).length || 0;
        const teachers_count = (await Teachers.find({}).exec()).length || 0;
        const courses_count = (await Courses.find({}).exec()).length || 0;

        return res.render('dashboard', { 
            user: req.user,
            studentCount: std_count,
            teacherCount: teachers_count,
            coursesCount: courses_count
        });

    } catch (err) {
        return res.status(500);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在Node.js中将查询转换为与mongodb一起使用 - how do I translate my query to use with mongodb in Node.js 如何将MongoDB查询捕获为字符串并将其显示在我的Node JS页面中(使用mongojs驱动程序)? - How do I capture a MongoDB query as a string and display it in my Node JS page (using the mongojs driver)? 如何使用MongoHQ和Node.js在Heroku上设置MongoDB? - How do I setup MongoDB on Heroku with MongoHQ and Node.js? 如何将mongodb与Node.js正确连接? - How do I connect mongodb with Node.js correctly? 如何使用 node.js 连接到 mongodb(并进行身份验证)? - How do I connect to mongodb with node.js (and authenticate)? 如何使变量存在于此node.js代码块之外? - How do I get a variable to exist outside of this node.js code block? 如何使用 node.js 操作 DOM? 我已经完成了我的 document.get 只是发现 node.js 无法识别它 - How do I manipulate the DOM using node.js? I have done my document.get only to find out node.js doesn't recognize it 我无法得到任何查询结果 Node.js MongoDB - I can't get any query result Node.js MongoDB 如何在 Node JS 变量上存储 HTML 表单输入? - How do I store HTML form inputs on a Node JS variable? 如何使用 Node.js 将变量传递给正则表达式? - How do I pass a variable into regex with Node js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM