【问题标题】:How to get a specific field in schema.pre() method?如何在 schema.pre() 方法中获取特定字段?
【发布时间】:2019-05-04 21:38:38
【问题描述】:

我在 mongoose 中使用 nodejs,我想在更新文档之前获取用户密码。我在更新之前使用schema.pre()方法调用,但是我不知道如何在这个方法中获取用户密码。

这是我的UserSchema.pre() 方法:

UserSchema.pre('update', function(next){
   var user = this;
   next();
});

和我的架构:

var UserSchema = new mongoose.Schema({

email: {
    type: String,
    required: true,
    minlength: 1,
    trim: true,
    unique: true
},
password: {
    type: String,
    required: true,
    minlength: 6
},
firstName: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
},
lastName: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
},
tokens: [{
    access:{
        type: String,
        required: true
    },
    token:{
        type: String,
        required: true
    }
}]
});

希望你能帮我解决这个问题, 谢谢。

【问题讨论】:

  • 请您将您的架构的定义添加到帖子中?

标签: node.js mongoose mongoose-schema


【解决方案1】:
UserSchema.pre('update', function(next){
   var user = this;
   console.log(user._update); // contains the fields to be be updated
   next();
});

当您更新单个用户时,我建议您改用 pre findOneAndUpdate 挂钩。

【讨论】:

    【解决方案2】:

    这对我有用,

    UserSchema.pre('update', function(next){
       var user = this['_doc'];
       console.log(user); // contains the fields to be be updated
       next();
    });
    

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 2019-03-24
      • 2019-07-06
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2020-12-04
      相关资源
      最近更新 更多