node.js - How to update model in mongoose with async validation (node/koa2) -


from client side, user has form fill can update either email or password.

they have enter current password in order validate request. after, if email address being modified email validator should run check new email address isn't registered user.

so, after user sends request client side following information:

{     userid: 'this id of entry in database',     currentpassword: 'current password check against 1 stored in database',     newpassword: 'new password, blank if user has not requested new password',     email: 'email address, same if user has not requested new email' } 

the code in route follows;

const req = ctx.request.body; const userid = ctx.request.body.userid;  const updatevalues = (user, password, email) => {     let update = {};      if (user.email != email) {         update['email'] = email     }     if (password.length > 0) {         update['password'] = user.generatehash(password)     }     return update; }  const opts = {     runvalidators: true, context: 'query' }  await user.findbyid(userid, async function (err, user) {     try {         await user.comparepassword(req['currentpassword'])         await user.update({_id: userid}, {$set: updatevalues(user, req['newpassword'], req['email'])}, opts, (error) => {             console.log(error)         })          return ctx.body = {             message: 'user modified',             user: user         }     }     catch (err) {         console.log(err)         ctx.body = {             err: err.message         }     } 

and here email section of model:

email: {     type: string,     required: true,     validate: {         validator: function (v, cb) {             this.model('user').find({email: v}, (err, docs) => {                 cb(docs.length == 0, 'email taken!');             })         }     } }, 

here comparepassword function (although part works fine);

userschema.methods.comparepassword = function (password) {     if (bcrypt.comparesync(password, this.password)) {         return     }     else {         throw new error('password\'s not match')     } } 

i've been trying read mongoose docs figure out, , method shown above variation of i've been reading documents section, async custom validator section , update validators , section.

currently, i'm getting following error;

typeerror: cannot use 'in' operator search '_id' in user 

i've tried lot of different things, varying degrees none have worked. i'm hoping can point me in right direction?


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -