MongoDb + Mongoose | How to hash array of passwords instead of a single password

天大地大妈咪最大 提交于 2020-01-16 09:11:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!