猫鼬节省一对多

时间:2018-01-01 11:58:49

标签: 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 = 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);

USER SCHEMA

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");
        })
    });
});

1 个答案:

答案 0 :(得分:3)

由于博客架构期望评论字段只是注释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");
    });
});