Hafiz Temuri
Hafiz Temuri

Reputation: 4122

pre('save') or pre('validate') doesn't trigger | Mongoose

pre('save') or pre('validate') does not trigger when I save the data. Although, it is saving the data without triggering the pre function. Not sure what I am doing wrong.

var userSchema = new Schema({...});

var User = module.exports = mongoose.model('User', userSchema);

userSchema.pre('save', function(next){ // tried with pre('validate')
    console.log('triggered...');
    next();
});

// adding a user
module.exports.addUser = function(user, callback){
    var newUser = new User(user);
    newUser.save(callback);
    //or
    User.create(user, callback);
}

Upvotes: 1

Views: 1119

Answers (2)

robertklep
robertklep

Reputation: 203329

Hooks only work if you define them before creating the model:

var userSchema = new Schema({...});

userSchema.pre('save', function(next){ // tried with pre('validate')
    console.log('triggered...');
    next();
});

var User = module.exports = mongoose.model('User', userSchema);

Upvotes: 2

hurricane
hurricane

Reputation: 6724

If you want to do it with async you need to define it with true option.

userSchema.pre('save', true, function(next){ // tried with pre('validate')
    console.log('triggered...');
    next();
});

You can look at HERE parallel and serial examples.

Upvotes: 0

Related Questions