【发布时间】: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