【问题标题】:bcryptjs does not work on insertMany (works fine on create)bcryptjs 在 insertMany 上不起作用(在创建时工作正常)
【发布时间】:2021-12-24 07:45:39
【问题描述】:

bcryptjs 版本:"bcryptjs": "^2.4.3"

猫鼬版:"mongoose": "^6.0.12"

我正在尝试在用户创建或密码更新时加密用户密码。当我使用User.create() 创建单个用户时,一切都按预期工作(密码已加密)。当我使用User.insertMany() 时,数据插入成功,但密码未加密。这是我的架构:

const userSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true
    },
    surname: {
      type: String,
      required: true
    },
    voterId: {
      type: String,
      required: true,
      unique: true
    },
    password: {
      type: String,
      required: true,
      unique: true,
    },
    votedFor: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Election'
      }
    ],
    finishedVoting: {
      type: Boolean,
      required: true,
      default: false
    },
    isAdmin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
)

userSchema.pre('save', async function(next) {
  // Only run this function if password was actually modified
  if (!this.isModified('password')) return next();

  // Hash the password with salt 10
  this.password = await bcrypt.hash(this.password, 10);

  next();
});

这是我尝试插入的一些示例数据:

const voters = [
  {
    name: "Sherali",
    surname: "Samandarov",
    voterId: "194199",
    password: "FA654644", //will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  },
  {
    name: "Sherali",
    surname: "Samandarov",
    voterId: "184183",
    password: "MB454644", //will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  },
  {
    name: "Sherali",
    surname: "Samandarov",
    voterId: "194324",
    password: "FA651684", //will be encrypted
    isAdmin: false,
    finishedVoting: false
    // votedFor: [Object], //
  }
]

我猜userSchema.pre('save', ...) 出于某种原因不会在insertMany() 上触发

【问题讨论】:

    标签: javascript mongodb mongoose bcryptjs


    【解决方案1】:

    解决了。

    我可以通过关注@victorkt's answer来解决问题:

    使用pre('validate') 而不是pre('save') 来设置 必填项目。 Mongoose 在保存之前验证文档,因此 如果存在验证错误,您的保存中间件将不会被调用。 将中间件从 save 切换到 validate 将使您的功能 在验证之前设置密码字段。

    所以,

    userSchema.pre('validate', async function(next) {
      // Only run this function if password was actually modified
      if (!this.isModified('password')) return next();
    
      // Hash the password with salt 10
      this.password = await bcrypt.hash(this.password, 10);
    
      next();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多