简体   繁体   中英

Behavior of this variable in Validation with Mongoose + Nodejs

I'm trying to run a validation process for a field in the mongoose schema. However, the behavior of the "this" variable is different than expected. Because according to the documentation at: http://mongoosejs.com/docs/validation.html#update-validators-and-this , this should reference the object of the template being saved. However, when debugging in VsCode the Local reference to this is correct, however, the reference pointed to by the "Watcher" is another, the class reference of the module. Can anyone tell me why this occurs? How to access the correct this reference in this context? VsCode Debug

Because you are using an arrow function for defining the validation method:

An arrow function expression has a shorter syntax than a function expression and does not have its own this , arguments , super , or new.target . These function expressions are best suited for non-method functions , and they cannot be used as constructors.

Source code changed to use function and worked.

const valOwnerId = function(value) {
   let self = this;
   let callback = (resolve, reject) => {
      Company.findOne({ numberId : value }).then( (company) => {
         if (company && (company.ownerId.toString() != self.ownerId.toString())) {
            throw new Error('Esta companhia já está cadastrada para outro usuário.');
         } else {
            return resolve(true); 
         }
      }, (error) => {
         reject(error);
      });
   };
   return new Promise(callback);
}
schema.path('numberId').validate( valOwnerId, 'Number ID `{VALUE}` is not valid.');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM