如何使用异步验证更新mongoose中的模型(node / koa2)

时间:2017-07-28 09:01:48

标签: node.js mongodb mongoose koa koa2

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

他们必须输入当前密码才能验证请求。之后,如果正在修改电子邮件地址,则应运行电子邮件验证程序以检查新电子邮件地址是否已经注册到其他用户。

因此,在用户从客户端发送请求后,我会收到以下信息:

{
    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文档来解决这个问题,上面显示的方法是我从Documents SectionAsync Custom Validator Section读取的内容的变体。和Update Validators and this Section

目前,我收到以下错误;

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

我尝试了很多不同的事情,但程度不同但都没有。我希望有人能指出我正确的方向吗?

0 个答案:

没有答案