问题
I have a json array containing data of almost 300 users. I am using (Mongoose)Model.InsertMany() for saving user data array to Mongodb. To hash a single user password i am using this guide: https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
but i want to hash passwords of all users at once. This guide uses 'save' function to hash but as i am using 'InsertMany()' to dump to Mongodb so how can i achieve hashing by using InsertMany()
回答1:
You can use pre save hook in your user model.
The problem is InsertMany does not work with pre save hook.
But using Model.create will call any hooks declared on your schema.
So you can use User.create() method to make it work.
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;
回答2:
Mongoose insertMany()
doesn't trigger the .save()
hook. So, you should hash all the passwords first then use insertMany()
function to insert them into database.
回答3:
you have to create pre
hooks on mongoose that will call before creating a document, in pre hook
function you can use bcrypt
a node library generate a hash string.
来源:https://stackoverflow.com/questions/58659742/mongodb-mongoose-how-to-hash-array-of-passwords-instead-of-a-single-password