Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert/Update record using mongoose

Tags:

mongoose

I am trying to insert a record into mongodb, using mongoose, but the record does not update when record is already in the database. Is there something I am doing wrong? The documentation for mongoose is not the easiest to follow for me.

models.fg_records.update({email:clean_email}, inactive_user, {update: true}, function (err) {
    if(err){
        throw err;
        console.log(err);
    } else {

        // send mail with defined transport object
        transport.sendMail(message, function(err, response) {
            if(err) {
                console.log(err);
                view('<ul><li>There was a problem sending an email to this user. Make sure you types it correctly.</li></ul>');
            } else {
                res.redirect('/records');
            }
        });

    }
});
like image 735
tony2 Avatar asked Nov 18 '12 23:11

tony2


People also ask

How do I update my Mongoose?

The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.

What is update query in Mongoose?

Mongoose | update() Function The update() function is used to update one document in the database without returning it.

What is the difference between updateOne and findOneAndUpdate?

What is the difference between findOneAndUpdate and updateOne? findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).


1 Answers

Try passing the option 'upsert' to the update function, instead of 'update', which is not a valid option documentation.

models.fg_records.update({email:clean_email}, inactive_user, {upsert: true}, function (err) { ... }):
like image 160
Errol Fitzgerald Avatar answered Nov 09 '22 19:11

Errol Fitzgerald