在MongoDB中引用多个集合
我的数据库中有三个集合:应用程序、评论和用户 应用程序将有多个评论,评论将有一个用户,用户将有多个评论 我真的需要他们团结在一起,我正在努力。我已经能够将评论附加到用户(反之亦然),但我无法将评论附加到应用程序。我在想,这一行动需要在发布到数据库进行审查时进行 我确实有所需的appId(它存储在审阅主体中),但我无法正确识别和更新数据库中的正确集合(应用程序)。我似乎在为这件事发狂 基本上,我需要引用审查所针对的应用程序和发布审查时审查的用户。我的所有模型都“正确”引用了其他集合(正如您演示的消息和用户组件) 有人能给我指出正确的方向吗?这是我到目前为止的帖子代码在MongoDB中引用多个集合,mongodb,mongoose,Mongodb,Mongoose,我的数据库中有三个集合:应用程序、评论和用户 应用程序将有多个评论,评论将有一个用户,用户将有多个评论 我真的需要他们团结在一起,我正在努力。我已经能够将评论附加到用户(反之亦然),但我无法将评论附加到应用程序。我在想,这一行动需要在发布到数据库进行审查时进行 我确实有所需的appId(它存储在审阅主体中),但我无法正确识别和更新数据库中的正确集合(应用程序)。我似乎在为这件事发狂 基本上,我需要引用审查所针对的应用程序和发布审查时审查的用户。我的所有模型都“正确”引用了其他集合(正如您演示的消
// SAVE A REVIEW TO DATABASE
router.post('/', function(req, res, next) {
var decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, function(err, doc) {
if (err) {
return res.status(404).json({
title: 'An error occurred',
error: err
});
}
var review = new Review({
content: req.body.content,
rating: req.body.rating,
app: req.body.appId,
user: doc
})
Application.findById(req.body.appId, function(err, doc) {
if (err) {
return res.status(404).json({
title: 'An error occurred',
error: err
});
}
review.save(function(err, result) {
if (err) {
return res.status(404).json({
title: 'An error occurred',
error: err
});
}
review.update(function(err, result) {
if (err) {
return res.status(404).json({
title: 'An error occurred',
error: err
});
}
doc.reviews.push(result);
doc.save();
res.status(201).json({
message: 'Saved review',
obj: result
});
});
});
});
型号:
Review Model:
var schema = new Schema({
content: {type: String, required: true},
rating: {type: Number},
dateCreated: {type: String},
app: {type: Schema.Types.ObjectId, ref: 'Application'},
user: {type: Schema.Types.ObjectId, ref: 'User'}
});
Application Model:
var schema = new Schema({
name: {type: String, required: true},
description: {type: String},
reviews: [{type: Schema.Types.ObjectId, ref: 'Review'}],
})
User Model:
var schema = new Schema({
firstName: {type: String, required: true},
lastName: {type: String, required: true},
password: {type: String, required: true},
passwordConfirm: {type: String, required: true},
email: {type: String, required: true, unique: true},
reviews: [{type: Schema.Types.ObjectId, ref: 'Review'}]
});
也许我在这件事上走错了方向,但我似乎迷路了
提前谢谢大家