我正在使用MERN技术栈,遇到一个问题:mongoose的findOne方法返回第一个找到的对象,即使条件不为真。
以下是我的用户模型:
{ local:{
username,
email,
password
},
google: {
googleId,
email,
name
}
}
我有一个名为 statics 的模式,用于查找电子邮件是否存在
userSchema.statics.findByEmail = async (email) => {
const localUser = await User.findOne({ "local.email": email });
const googleUser = await User.findOne({ "goolge.email": email });
return { localUser, googleUser };
};
在我的API中,在添加用户之前,我使用findByEmail在我的数据库中搜索该用户。
router.post("/register", async (req, res) => {
const user = await User.findByEmail(req.user.email);
})
如果我的数据库中没有文档,API可以完美地运行。但是,如果至少有一个文档,它总是返回我的数据库中的第一个文档,即使
req.user.email
不在我的数据库中。
goolge.email
中有一个打字错误,现已修复并正常工作。 - Mohamed EssamdeleteMany
是否工作方式相同吗? - Garr Godfrey