Search code examples
javascriptmongodbmongoosemongoose-schema

How can I access the update object in findOneAndUpdate pre hook?


Consider this

const myUpdate = {address: 'abc'};
const update = await myModel.findOneAndUpdate({_id: 'a0123'}, myUpdate);

myschema.pre('findOneAndUpdate', function() {
    const query = this.getQuery(); // {_id: 'a0123'}
    // How can I access and modified `myUpdate` here 
    const myUpdate = this.getUpdate(); // ??
})

I'm using mongoose 7.2.2


Solution

  • Seems like an issue with Mongoose, getUpdate returns the update object in the post hook, but not in the pre-hook, for some reason. You can use _update, in the pre-hook like this:

    const myUpdate = {address: 'abc'};
    const update = await myModel.findOneAndUpdate({_id: 'a0123'}, myUpdate);
    
    myschema.pre('findOneAndUpdate', function() {
        const query = this.getQuery(); 
        const myUpdate = this._update;
    })