saytri
saytri

Reputation: 99

Mongoose save one to many

I have following model in mongoose in which blog have many comments

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

Comment Model

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

I am using following function to save the comment in related blog post. I am able to save the comment but comment is saved as embedded document while I am expecting that blog should only have _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");
        })
    });
});

Upvotes: 2

Views: 2258

Answers (1)

chridam
chridam

Reputation: 103365

Since the blog schema is expecting the comments fields an array of just comment ids, you would need to save the comment first then push the new comment id to the blog:

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

Upvotes: 5

Related Questions