带有 'either or' 查询的 Mongoose findOne
Mongoose findOne with 'either or' query
我有一个 Mongo 用户数据库,我正在使用 Mongoose 进行查询。我想做 findOne 来确定用户是否已经存在。我希望它首先搜索用户是否已经存在电子邮件,如果不存在,则应该搜索以查看用户是否存在 phone。这是否必须在 2 个单独的查询中完成,还是可以合并为一个?
User.findOne({ email: req.body.email }).exec(function(err, user){
if (user) //user already exists with email
else //no users with that email but we haven't checked phone number yet!
});
为什么不直接使用 $or
运算符?
User.findOne({$or: [
{email: req.body.email},
{phone: req.body.phone}
]}).exec(function(err, user){
if (user) {} //user already exists with email AND/OR phone.
else {} //no users with that email NOR phone exist.
});
这是伪SQL
等价物:
SELECT * FROM users WHERE email = '%1' OR phone = '%2'
我有一个 Mongo 用户数据库,我正在使用 Mongoose 进行查询。我想做 findOne 来确定用户是否已经存在。我希望它首先搜索用户是否已经存在电子邮件,如果不存在,则应该搜索以查看用户是否存在 phone。这是否必须在 2 个单独的查询中完成,还是可以合并为一个?
User.findOne({ email: req.body.email }).exec(function(err, user){
if (user) //user already exists with email
else //no users with that email but we haven't checked phone number yet!
});
为什么不直接使用 $or
运算符?
User.findOne({$or: [
{email: req.body.email},
{phone: req.body.phone}
]}).exec(function(err, user){
if (user) {} //user already exists with email AND/OR phone.
else {} //no users with that email NOR phone exist.
});
这是伪SQL
等价物:
SELECT * FROM users WHERE email = '%1' OR phone = '%2'