我有两种猫鼬模型:
如果用户有任何喜欢的业务,我需要返回合并结果。现在,我正在实现自己的目标,但我认为这是不好的做法。如果有人有更好的方法,请指出我的错误。
最喜欢的型号:
const mongoose = require("mongoose");
const favouriteSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
userId: {
type: mongoose.Schema.Types.ObjectId,
require: true,
ref: "userModel"
},
businessId: {
type: mongoose.Schema.Types.ObjectId,
require: true,
ref: "businessModel"
},
favouriteStatus: { type: Boolean, require: true, default: false }
});
module.exports = mongoose.model("favouriteModel", favouriteSchema);
用户模型:
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
phone: {
type: Number,
required: true,
unique: true
//match: /^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$/
},
profileImage: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
password: { type: String, required: true }
});
module.exports = mongoose.model("UserModel", userSchema);
用户登录控制器:
router.post('/login', UserValidation.loginUser, (req, res, next) => {
//express validation
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
UserModel.findOne({ phone: req.body.phone })
.select()
.exec()
.then(user => {
console.log({ userdata: user });
if (user === null) {
return res.status(401).json({
success: false,
message: 'phone not exits',
});
}
//password convert to hast and then match
bcrypt.compare(req.body.password, user.password, (err, result) => {
if (err) {
return res.status(401).json({
success: false,
message: err,
});
}
if (result) {
const token = jwt.sign(
{
phone: user.phone,
userId: user._id,
},
process.env.JWT_KEY,
{
expiresIn: '1h',
}
);
// find favorite of this user
favouriteModels
.find({ userId: user._id })
.select('favouriteStatus')
.then(userWithFavorite => {
if (userWithFavorite.length > 0) {
return res.status(200).json({
success: true,
message: 'AUTH SUCCESS',
token: token,
data: { user, userWithFavorite },
});
} else {
console.log({ _id: user._id });
return res.status(200).json({
success: true,
message: 'AUTH SUCCESS',
token: token,
data: { user },
});
}
})
.catch(err => {
res.status(500).json({
status: 500,
success: false,
message: err,
});
});
} else {
return res.status(401).json({
success: false,
message: 'password is incorrect',
});
}
});
})
.catch(() => {
res.status(500).json({
success: 500,
success: false,
});
});
});
答案 0 :(得分:1)
当您需要访问引用的架构时,可以使用populate
,因此在您的情况下:
favouriteModels
.find({ userId: user._id })
.populate("userModel")
.exec()
.then(user => {
res.status(200).json(user); // access "userSchema" with user.userSchema
});
在mongoose documentation中了解有关此内容的更多信息。