![](/img/trans.png)
[英]How to save one document into two different collections of same database in mongodb
[英]Searching for a user by email address in two collections in database MONGODB at the same time
我的數據庫 mongodb 中有兩個集合tutors
和users
。 我在控制器中有一個signin
功能。 在signin
內部,我有tutors
和users
。 我應該添加什么條件才能在tutors
和users
集合中搜索users
?
控制器/授權
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}
});
}
});
};
這是設計數據庫模型的一種糟糕方式。 而是創建一個單一的集合,稱其為users
,它可以有一個像userType
這樣的字段,可以是Tutor
或User
用戶模型 User.js
var userSchema = {
type: String,
enum: ['tutor', 'user'],
default: 'user'
}
並像這樣查詢:
Tutor.findOne(...) // to query for a tutor
User.findOne(...) // to query for a user
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.