Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying mongoose document on pre hook of findOneAndUpdate()

I have a mongoose schema as such

var schema = new Schema({
    id:Number
    updated_at:Date
});

I am using findOneAndUpdate() to update this model as such

model.findOneAndUpdate(
    { id: json.id },
    json,
    {
        upsert: true,
        runValidators: true
    })
    .then(() => {
        recordsUpdated++;
    })
    .catch((err) => {
        this.emit('error', err);
    });

The value being passed in json is not correct and I need to make some modifications to it. I am looking for a pre hook to do the modification. I have tried

faction.pre('findOneAndUpdate', function (next) {
   this.update({ $set: { updated_at: this.getUpdate().updated_at * 1000 } });
   next();
});

In short I want to convert the timestamp which is in seconds to milliseconds before updating the database, but this doesn't work.

like image 894
Sayak Mukhopadhyay Avatar asked Dec 02 '22 12:12

Sayak Mukhopadhyay


1 Answers

After blindly throwing stones all around, what worked for me was

schema.pre('findOneAndUpdate', function (next) {
    this._update.updated_at *= 1000;
    next();
});

In short one needs to modify the document present in the _update property.

like image 136
Sayak Mukhopadhyay Avatar answered Jan 17 '23 16:01

Sayak Mukhopadhyay