我在 Mongoose 中有以下模型,其中博客有很多评论
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var blogScheam = Schema({
title: String,
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
});
module.exports = mongoose.model('Post', blogScheam);
评论模型
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var commentSchema = Schema({
comment: String,
user: { type: Schema.Types.ObjectId, ref: 'User' }
});
module.exports = mongoose.model('Comment', commentSchema);
用户架构
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var userScheam = Schema({
name: String,
age: Number,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
module.exports = mongoose.model('User', userScheam);
我正在使用以下功能来保存相关博客文章中的评论。我可以保存评论,但评论被保存为嵌入文档,而我期望博客应该只有 _id
app.post('/comment', (req, res) => {
Blog.findById({ _id: req.body._id }).then(blog => {
var comment = new Comment({
comment: req.body.title
})
blog.comments.push(comment2);
blog.save().then(() => {
res.render("details");
}).catch(() => {
res.render("details");
})
});
});
最佳答案
由于博客架构期望评论字段仅包含评论 ID 的数组,因此您需要先保存评论,然后将新评论 ID 推送到博客:
app.post('/comment', (req, res) => {
const comment = new Comment({
comment: req.body.title
});
comment.save().then(c => (
Blog.findByIdAndUpdate(req.body._id,{ '$push': { 'comments': c._id } });
)).then(() => {
res.render("details");
}).catch(() => {
res.render("details");
});
});
关于javascript - Mongoose 保存一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48049466/