Вы можете использовать хук предварительного сохранения в своей пользовательской модели.
Проблема в том, что InsertMany не работает с хуком предварительного сохранения.
Но использование Model.create вызовет любые хуки, объявленные на вашемсхема.
Таким образом, вы можете использовать метод User.create (), чтобы заставить его работать.
https://mongoosejs.com/docs/api/model.html#model_Model.create
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
userSchema.pre('save', async function(next) {
this.password = await bcrypt.hash(this.password, 12);
next();
});
const User = mongoose.model('User', userSchema);
module.exports = User;