【问题标题】:Mongoose Schema pre save doesn't return on call to next()Mongoose Schema pre save 不会在调用 next() 时返回
【发布时间】:2020-03-17 15:06:22
【问题描述】:

我正在尝试构建一个需要用户注册和登录功能的简单应用程序。我已将用户架构定义如下:

// User Schema
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true, 
        trim: true,
    },
    password: {
        type: String,
        required: true,
        minlength: 7,
        trim: true,
        validate(value) {
            if (value.toLowerCase().includes('password')) {
                throw new Error('Password cannot contain "password"')
            }
        }
    },
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    name: {
        // TODO : Add validation for name
        type: String,
        required: true
    },
    mobile:{
        // TODO : Add validation for mobile numbers
        type: String
    }
}, {
    timestamps: true
});

userSchema.pre('save', async function (next) {
const user = this
console.log("inside pre")

if (user.isModified('password')) {
    console.log("about to hash ", user.password )
    user.password = await bcrypt.hash(user.password, 8)
    console.log("hashed pwd ", user.password )
}
next();
})

在我的路线中,我有以下内容:

router.post('/users', async (req, res) => {

    const user = new User(req.body)

    try {
        console.log("about to save ")
        await user.save()
        console.log("About to gen token")
        const token = await user.generateAuthToken()
        console.log("About to send  res")
        res.status(201).send({ user, token })
    } catch (e) {
        res.status(400).send(e)
    }
})

原始密码和明文都会打印,但从不发送响应。保存函数调用之后的行永远不会被执行。为什么会发生这种情况?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    从.pre('save' 中删除async。你不能将 Promise 与回调混为一谈。你可以使用任何一个,但你不能同时使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 2021-01-08
      • 2018-11-17
      • 2018-04-22
      • 2014-03-22
      • 2017-08-02
      • 2016-07-14
      相关资源
      最近更新 更多