首页 > 解决方案 > TypeError: login.findOne(...).toArray 不是函数

问题描述

我有这个功能,基本上是从前端表单获取用户输入的用户名和密码,然后在mongodb中检查:

 app.post('/login', (req, res, next) => {

    var username = req.body.username;
    var password = req.body.password;
    //connecting to the mongo client
  client.connect().then (() => {
    
    //defining database name and collection
    const database = client.db("myFirstDatabase");
    const login = database.collection("login");
    
    //connecting to the mongo client
    MongoClient.connect(uri, function(err, db) {
        if (err) throw err;


      //finding all documents inside array
        login.findOne({"username": username}).toArray(function(err, result) {
            if (err) throw err;

            result.forEach(results => 
                bcrypt.compare(password, results.password, function(err, result) {
                    if (result === true) {
                        req.session.loggedin = true
                        next()
                    } else {
                        res.redirect('/login')
                    }
                })
            );

            db.close();
        });
    });
})
})

但是,它给了我这个错误:

TypeError: login.findOne(...).toArray is not a function

我以前从未遇到过这个错误。我该如何解决?

标签: node.jsmongodb

解决方案


试试这个方法

login.findOne({"username": username}, function(err,user) 
{ console.log(user); });

推荐阅读