[英]How to check if an embedded document exists in database before saving in Mongoose
I'm making a basic authentication system using Express, Mongoose and PassportJS. 我正在使用Express,Mongoose和PassportJS构建基本的身份验证系统。 What I want to do is to check the database if the entered username and password already exist in the database.
我要做的是检查数据库,如果输入的用户名和密码已经存在于数据库中。 Here's my sample code below:
这是下面的示例代码:
//Post: /signup
app.post('/signup', function (req, res) {
var username = req.body.person.user.username;
var password = req.body.person.user.password;
Person.user.find({'username': username}, function (err, user) {
if (err) {
console.log(err.name);
} else {
console.log('User Found');
}
});
});
The problem is it returns this kind of error: 问题是它返回这种错误:
TypeError: Cannot call method 'find' of undefined
Could someone please help me. 有人可以帮我吗。
As robertklep pointed, you are not checking correctly for an user's existence. 正如robertklep指出的那样,您没有正确检查用户的存在。 Also, since username is most likely unique, you can just use findOne (findOne() returns a single object while find() may also return a single object but will wrap it in an array).
另外,由于用户名很可能是唯一的,因此您可以使用findOne(findOne()返回单个对象,而find()也可能返回单个对象,但会将其包装在数组中)。
Person.findOne({'username': username}, function (err, user) {
if (err) {
console.log(err.name);
return;
}
if (!user)
console.log('User not Found');
return;
}
console.log('User found');
});
I think you're looking for this: 我认为您正在寻找这个:
Person.find({ 'user.username' : username }, ...)
FWIW, if the callback isn't called with an error it doesn't mean a user was found, it just means that there were no errors performing the query. FWIW,如果没有错误地调用回调函数,则并不表示已找到用户,这仅意味着执行查询没有错误。 But
user
can still be null, meaning that the query didn't have any matching results. 但是
user
仍然可以为null,这意味着查询没有任何匹配结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.