Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.77k stars 3.8k forks source link

Overwrite data in pre-validate hook #8052

Closed alexcagliari87 closed 4 years ago

alexcagliari87 commented 4 years ago

Hi all,

i have a problem using the pre validate hook in a mongoose model.

What i want is to "overwrite" in the pre-validate hook the data that will bepassed to validation and post-validate .

My code is:

bookSchema.pre('validate', async function () {

  let test = Object.assign({},this._doc);

  ...

  test.field = 'abc';

  ...

  //What i have to do to pass "test" var to validate?

});

I need to pass my "test" object to validate and post validate method...I didn't find anything in documentation...

I need to overwrite passed data....How can i do?

Ncifra commented 4 years ago

You could just create a field inside the global scope like:

bookSchema.pre('validate', async function () {

  this.test = Object.assign({},this._doc);

  ...

  this.test.field = 'abc';

  ...

});

Also check out the other issue you opened, you seem to not respond anymore to your issues.

vkarpov15 commented 4 years ago

@Ncifra 's solution is correct, although you should use the $locals property instead

this.$locals.test = Object.assign({}, this._doc);

Also, why are you copying the document and what do you mean by "passing my 'test' object to validate"?