EvonuX
EvonuX

Reputation: 189

Mongoose - accessing data from a virtual node in 'pre' save hook

I need to use data from a newly created document and use that data to update a value using a 'pre' hook.

For example, my model is:

...
title: {
  type: String,
  required: true
},
company: {
  type: mongoose.Schema.ObjectId,
  ref: 'Company',
  required: true
}

...

And the 'pre' hook is:

jobSchema.pre('save', function(next) {
  const jobTitle = slugify(this.title, { lower: true })
  const companyName = slugify(this.company.name, { lower: true })
  this.slug = jobTitle + companyName
  next()
})

I'm not able to access this.company in the hook and I'm not sure how it can be done.

Upvotes: 0

Views: 226

Answers (1)

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

Since company is type of ObjectId, you can use findById to have access

jobSchema.pre('save', function(next) {
    let job = this;
    Company.findById(job.company, function (err, company) {
        if(err) return next(err);
        const jobTitle = slugify(job.title, { lower: true })
        const companyName = slugify(company.name, { lower: true })
        job.slug = jobTitle + companyName
        next();
    });
});

Upvotes: 1

Related Questions