Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

How to update existing object with additional data

$
0
0

The project is created with nodejs and mongoose. What I am trying to do is to update the existing model with addition data (which is a comment, in that case).

This is the model and its methods:

const bugSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: String,
        required: true
    },
    time: {
        type: String,
        required: true
    },
    assignedTo: {
        type: String,
        required: true
    },
    assignedBy: {
        type: String,
        required: true
    },
    status: {
        type: String,
        required: true
    },
    priority: {
        type: String,
        required: true
    },
    comments: {
        comment:[
            {
                user:{
                    type: String,
                    required: true
                },
                content: {
                    type: String,
                    required: true
                }
            }
        ]
    }

});

bugSchema.methods.addComment = function(comment){
    const username = comment.user;
    const content = comment.content;
    console.log(comment);
    const updatedComments = [...this.comments];
    updatedComments.push({
       user : username,
       content: content
    });
    this.comments = updatedComments;
    return this.save();

};

The controller, which is passing the information from the form:

exports.postComment =  (req,res,next) =>{
    const bugId = req.body.bugID;
    const name = req.session.user.fullName;
    const content = req.body.content;
    const prod = {name, content};

    Bug.findById(bugId).then(bug =>{
        return bug.addComment(prod);
    })
        .then(result =>{
            console.log(result);
        });


};

I am getting a following error:

(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable

Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>