Rohit Bhalke
Rohit Bhalke

Reputation: 147

How to find a document from mongodb using mongoose based on query and then insert some data to it and save back?

I have my Model as

var Model = {"name":String,"email":String,"notes":[{"time":Date,"title":String,"description":String}]

And I want to find document based on the email, and then add a note to the array. And then save it back. What I tried is,

var updatedNote = {};     
Model.findOne({'email':'[email protected]'},function(err, note){
    for(var property in note._doc){
        if(note._doc.hasOwnProperty(property)){
            updatedNote[property] = note._doc[property];
        };
    }
    updatedNote.notes.push(newNote);
    note._doc = updatedNote;
    note.save(function(err){
        if(err){
            console.log(error);
        }
        else {
            res.redirect('/notes');
        }
    })
});

But it is throwing error as "Object does not have save method". I don't want to use findByIdAndUpdate() as i am leaving this responsibility of generating id on mongo.

Upvotes: 0

Views: 48

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

I don't understand what most of that code is doing. If I wanted to add a note to the document (I'm assuming newNote is defined elsewhere), I'd just do:

Model.findOne({'email':'[email protected]'},function(err, note){

     note.notes.push(newNote);
     note.save(function(err){});
});

Upvotes: 1

Related Questions