Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set update timestamp in upsert operation in Mongoose?

I want to set the update timestamp only for updating the record (and insert timestamp for new record) in the upsert operation.

self.model.update({Id: obj.Id}, obj, {upsert: true}, function(err){
    if (err) {
        return;
    }

    //...

});

Is there anyway to handle this?

There is a pre.save middleware I could use maybe, but is there any way tell whether current operation is insert or update?

Thanks in advance!

like image 627
zs2020 Avatar asked Oct 05 '22 03:10

zs2020


1 Answers

You can't do it automatically. You can do it using $set: { timestamp: Date.now() } on upsert.

There is a closed issue in mongoose bugtracker discussing this, here: defaults are ignored on upsert

A little late, but hope that helps someone!

like image 115
jperelli Avatar answered Oct 13 '22 10:10

jperelli