我有一个类似的架构:
const CustomerSchema = new Schema({
email: { type: String, required: true, unique: true },
flags: {
marketingConsent: { type: Booleam, required: true },
},
});
当我结识新客户时:
const customer = new Customer({ email, marketingConsent });
1。)是否可以在预保存钩子中访问传递到构造函数(email,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();
});
答案 0 :(得分:1)
是的,可以使用pre save钩子中的数据
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
的值而导致的错误。
我希望这对您有帮助...