[英]user.findOne() always returns null
I am trying to get mongoose return data from local MongoDB instance.我正在尝试从本地 MongoDB 实例获取 mongoose 返回数据。 Eveything else is running fine.
其他一切都运行良好。 The form is giving data to passport.
该表格正在向护照提供数据。 I have also inserted data into mongodb manually.
我还手动将数据插入到 mongodb 中。 The only error is in user.findOne.
唯一的错误是在 user.findOne 中。 When I print user into console, instead of returning some data it returns null
当我将用户打印到控制台时,它没有返回一些数据,而是返回 null
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/member');
// authentication using passport
passport.use(new LocalStrategy({
usernameField: 'user',
passwordField: 'password'
},
function (username, password, done) {
User.findOne({ user: username }, function (err, user) {
// console.log(user, username, password);
if (err) {
console.log(`Error in configuring passport-local \n ${err}`);
return done(err);
}
if (!user) {
console.log(`Invalid username or password!!`)
return done(null, false);
}
return done(null, user);
});
}
));
My schema:我的架构:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
user: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
dept: String,
yr: Number,
name: {
type: String
}
}, {
timestamps: true
});
module.exports = mongoose.model('member_list', userSchema, 'member_list');
Here's my full code: https://github.com/krush11/site这是我的完整代码: https://github.com/krush11/site
Let me know if you need any more info如果您需要更多信息,请告诉我
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/member');
// authentication using passport
passport.use(new LocalStrategy({
usernameField: 'user',
passwordField: 'password'
},
async function (username, password, done) {
await User.findOne({ user: username }, function (err, user) {
// console.log(user, username, password);
if (err) {
console.log(`Error in configuring passport-local \n ${err}`);
return done(err);
}
if (!user) {
console.log(`Invalid username or password!!`)
return done(null, false);
}
return done(null, user);
});
}
));
The function looks good but try making it asynchronous then await
the query from the database. function 看起来不错,但尝试使其异步,然后
await
来自数据库的查询。 Take a look at the modification I made to your code.看看我对您的代码所做的修改。 You might also want to refactor your code and use promises instead of callback and wrap everything inside of
try{} catch{}
block.您可能还想重构代码并使用 Promise 而不是回调并将所有内容包装在
try{} catch{}
块中。
But making the function asynchronous and awaiting the query will fix the issue, this is because the findOne()
method actually returns a query and might not have completed before you console it.但是使 function 异步并等待查询将解决此问题,这是因为
findOne()
方法实际上返回了一个查询,并且在您控制台之前可能尚未完成。
Let me know if you still have any issue.如果您还有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.