Javascript 猫鼬拯救一对多
我在mongoose有以下模式,其中博客有很多评论Javascript 猫鼬拯救一对多,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我在mongoose有以下模式,其中博客有很多评论 var mongoose = require('mongoose') , Schema = mongoose.Schema var blogScheam = Schema({ title: String, comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] }); module.exports
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");
});
});