[英]Searching for a user by email address in two collections in database MONGODB at the same time
I have two collections tutors
and users
in my database mongodb.我的数据库 mongodb 中有两个集合tutors
和users
。 I have a signin
function in the controller.我在控制器中有一个signin
功能。 Inside signin
I have tutors
and users
.在signin
内部,我有tutors
和users
。 What condition should I add so that it searches for a user in both the tutors
and users
collections?我应该添加什么条件才能在tutors
和users
集合中搜索users
?
controllers/auth控制器/授权
const User = require('../models/user');
const Tutor = require('../models/tutor');
module.exports.signin = (req, res) => {
const {email, password, remember} = req.body;
//User
User.findOne({email}).exec((err, user) => {
if(err || !user) {
return res.status(400).json({
error: 'User with that email does not exist. Please signup'
});
}
if(!user.authenticate(password)) {
return res.status(400).json({
error: 'Email and password do not match'
});
}
const {_id, name, surname, email} = user;
if (remember) {
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET, {expiresIn: '7d'});
return res.json({
token,
user: {_id, name, surname, email}
});
} else {
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET, {expiresIn: '2m'});
return res.json({
token,
user: {_id, name, surname, email}
});
}
});
//tutor
Tutor.findOne({email}).exec((err, tutor) => {
if(err || !tutor) {
return res.status(400).json({
error: 'Tutor with that email does not exist. Please signup'
});
}
if(!tutor.authenticate(password)) {
return res.status(400).json({
error: 'Email and password do not match'
});
}
const {_id, name, surname, email} = tutor;
if (remember) {
const token = jwt.sign({_id: user._id}, process.env.JWT_SECRET, {expiresIn: '7d'});
return res.json({
token,
tutor: {_id, name, surname, email}
});
} else {
const token = jwt.sign({_id: tutor._id}, process.env.JWT_SECRET, {expiresIn: '2m'});
return res.json({
token,
tutor: {_id, name, surname, email}
});
}
});
};
This is a bad way to design your database model.这是设计数据库模型的一种糟糕方式。 Instead create a single collection, call it users
and it can have a field like userType
that can be either Tutor
or User
而是创建一个单一的集合,称其为users
,它可以有一个像userType
这样的字段,可以是Tutor
或User
User model User.js用户模型 User.js
var userSchema = {
type: String,
enum: ['tutor', 'user'],
default: 'user'
}
and query like this:并像这样查询:
Tutor.findOne(...) // to query for a tutor
User.findOne(...) // to query for a user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.