node.js - MongoDB:findOne 返回 null 但文档存在于集合中

标签 node.js mongodb

我正在尝试在服务器端发送电子邮件和密码并检查是否存在具有这些值的文档(确实存在),但是当我控制台记录查询中的 results 时,它为空.

这是 users 集合中的文档:

{
    "_id" : ObjectId("580bcf9874ae28934705c0fc"),
    "email" : "johndoe@gmail.com",
    "password" : "pass"
}

这是我在服务器端发送的内容:

{"email":"johndoe@gmail.com","password":"pass"}

这是我的代码(已更新):

mongo.connect('mongodb://localhost:27017', function (err, db) {

    if (err) {
    console.log("error: " + err); // logs nothing
    } else {

        var users = db.collection("users");
        var tasks = db.collection("tasks");

        app.post("/login", function(req, res) {

            var emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            var userInDb;
            var userEmail = req.body.email;
            var userPassword = req.body.password;

            console.log(req.body.email); // logs "johndoe@gmail.com"
            console.log(req.body.password); // logs "pass"

            if (!userEmail || !userPassword) {
                return res.sendStatus(403);
            } else if ( !emailRegex.test(userEmail)) {
                return res.sendStatus(403);
            } else {

                users.findOne( { "email": userEmail, "password": userPassword }, function(err, results) {

                    console.log(results); // logs "null"

                    if(err) {
                      console.log("error: " + err); // logs nothing
                      res.sendStatus(403);
                    } else {
                      console.log("here"); // logs "here"
                      res.sendStatus(200);
                    }

                  });
              }
          });
       }
    });

最佳答案

每次传递带有错误参数的回调时,您有责任检查是否传递了错误,如果是,则进行处理。

在您的代码中,您有两个这样的回调:

mongo.connect('mongodb://localhost:27017', function (err, db)
users.findOne( { "email": userEmail, "password": userPassword }, function(err, results)

它们中的任何一个都可以返回一个可能解释问题的错误对象。 将以下内容添加到每个回调的第一行:

if (err) {
  return console.log("error: " + err);
}

关于node.js - MongoDB:findOne 返回 null 但文档存在于集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40353972/

相关文章:

javascript - 在javascript中对PCM音频缓冲区进行下采样

javascript - Mongoose 不加入两个集合

node.js - 无法找到 id 并更新和增量子文档 - 返回 null Mongoose/mongoDB

php - Doctrine2 ODM 限制不起作用/mongodb

javascript - 如何在javascript中获取数组对象内的对象?

node.js - 错误!在树莓派 3 型号 b 上安装 Node 串行端口

node.js - Mocha 可以测试一次加载需求吗?

mysql - 如何在sequelize中使用内连接

java - Spring 是否有针对 mongoDB 的 @MappedSuperclass 等效注释?

node.js - nodemon - 应用程序崩溃 - 启动前等待文件更改