I have two collections tutors
and users
in my database mongodb. I have a signin
function in the controller. Inside signin
I have tutors
and users
. What condition should I add so that it searches for a user in both the tutors
and users
collections?
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
User model 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.