【问题标题】:Get mongoose constructor data in pre-save hook在预保存钩子中获取猫鼬构造函数数据
【发布时间】:2019-07-09 00:24:50
【问题描述】:

我有一个类似的架构:

const CustomerSchema = new Schema({
  email: { type: String, required: true, unique: true },
  flags: { 
    marketingConsent: { type: Booleam, required: true },
  },
});

当我结交新客户时:

const customer = new Customer({ email, marketingConsent });

1.) 是否可以在预保存挂钩中访问传递给构造函数(电子邮件、marketingConsent)的数据?

2.) 如果不是,那么直接从构造函数设置嵌套对象的正确方法是什么?

如果我这样做:

const customer = new Customer({
  email,
  ["flags.canMarket"]: consentValue,
});

await customer.save();

我得到错误:

Customer validation failed: flags.canMarket: Path `flags.canMarket` is required.

预存如下:

CustomerSchema.pre("save", function(next) {
  const self = this;

  if (self.isNew) {
    // Set passed in marketingConsent value.
  }

  next();
});

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    是的,可以使用预保存挂钩中的数据,

    CustomerSchema.pre("save", { query: true,document: true  }, function (error, data, next) {
    const self = this;
    // here you can access the data variable to use your data. for ex:
    console.log(data.email);
    console.log(data.marketingConsent)
    if (self.isNew) {
     // Set passed in marketingConsent value.
    }
    
    next();
    });
    

    你得到的错误是因为你没有传递flags.canMarket的值。

    我希望这会有所帮助...

    【讨论】:

    • 感谢您的回答。有没有办法在构造函数中传递flags.canMarket
    • 实际上,我的代码运行良好——其他地方出错了。
    猜你喜欢
    • 2013-08-14
    • 2018-03-04
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多