Please consider the following parentSchema
and childSchema
:
const parentSchema = new mongoose.Schema({
name: String,
children: [{ type: mongoose.Schema.Types.ObjectId, ref: "Child" }],
});
const childSchema = new mongoose.Schema({
name: String,
parent: { type: mongoose.Schema.Types.ObjectId, ref: "Parent" },
});
How do I access the name of the parent within a post middleware of the childSchema?
I am trying the code below but parent
is assigned the ObjectId instead of the actual parent model.
childSchema.post("save", async function (child) {
const parent = child.populate("parent").parent;
});
What's the right way to do this?
If you want to populate something after the initial fetch you need to call execPopulate
-- e.g.:
childSchema.post("save", async function (child) {
try {
if (!child.populated('parent')) {
await child.populate('parent').execPopulate();
}
const parent = child.populate("parent").parent;
} catch (err) {}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With