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

我以前从未遇到过这种错误。我该怎么解决这个问题?

尝试这种方式

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

FindOne的意思是,它只给出一个对象,所以不能得到数组。如果你使用find,那么你可以使用find().toArray()

最新更新