如何用asynchronousvalidation更新mongoose模型(node / koa2)

从客户端,用户有一个表格填写他们可以更新他们的电子邮件或密码。

他们必须input当前密码才能validation请求。 之后,如果电子邮件地址正在被修改,那么电子邮件validation器应该运行以检查新的电子邮件地址是否已经被注册到另一个用户。

所以,在用户从客户端发送请求后,我得到以下信息:

{ userId: 'This is the ID of their entry in the database', currentPassword: 'Current password to check against one stored in database', newPassword: 'New password, will be blank if user has not requested a new password', email: 'Email address, will be the same if user has not requested a new email' } 

我的路线代码如下:

 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 successfully modified', user: user } } catch (err) { console.log(err) ctx.body = { err: err.message } } 

这里是模型的电子邮件部分:

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

这里也是comparePassword函数(虽然这部分工作正常);

 UserSchema.methods.comparePassword = function (password) { if (bcrypt.compareSync(password, this.password)) { return this } else { throw new Error('password\'s do not match') } } 

我一直在尝试阅读mongoose文档来解决这个问题,上面显示的方法是我从文档部分 , asynchronous自定义validation器部分和更新validation器和本节读取的变体。

目前,我收到以下错误;

 TypeError: Cannot use 'in' operator to search for '_id' in User 

我尝试了很多不同的东西,不同程度的,但没有任何工作。 我希望有人能把我指向正确的方向?