Pawan Bhandarkar
Pawan Bhandarkar

Reputation: 304

Mongoose Schema pre save doesn't return on call to next()

I'm trying to build a simple application that requires user sign up and login functionality. I have defined the user schema as follows:

// 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();
})

and in my routes, I have the following:

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)
    }
})

Both the original password and the plaintext prints but the response is never sent. The line right after the save function call never gets executed. Why might this be happening?

Upvotes: 0

Views: 95

Answers (1)

samura
samura

Reputation: 4395

Remove the async from the .pre('save'. You cannot mix promises with callbacks. You can use either, but you cannot use both.

Upvotes: 1

Related Questions