Colin Ricardo
Colin Ricardo

Reputation: 17239

Get mongoose constructor data in pre-save hook

I have a schema like:

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

When I make a new customer:

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

1.) Is it possible to access the data passed into the constructor (email, marketingConsent) in the pre-save hook?

2.) If not, what's the right way to set nested objects directly from the constructor?

If I do:

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

await customer.save();

I get the error:

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

The pre-save looks like this:

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

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

  next();
});

Upvotes: 0

Views: 688

Answers (1)

PANKAJ NAROLA
PANKAJ NAROLA

Reputation: 164

Yes, It's possible to use the data in the pre save hooks,

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();
});

the error you got because you haven't passed the value of flags.canMarket.

I hope this helps...

Upvotes: 1

Related Questions