Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter documents using a dynamic variable that depends on another document using Node.js and mongoose?

I'm a bit stuck at this point... I need to add a new property to a document that varies according to the values of that same document and the values of another document. I set an example to make it better understood.

I have a Candidate Schema:

const CandidateSchema: Schema<ICandidate> = new Schema({
    role: {type: String},
    yearsOfExperience: {type: Number},
    compatibility: {type: Number} // Dynamic prop
});

And a Job Schema

const JobSchema: Schema<IJob> = new Schema({
    title: {type: String},
    postDate: {type: String},
    requirements: {
      role: {type: String},
      yearsOfExperience: {type: Number}
    }
});

Now I need to add to the candidate's "compatibility" property a new value based on the values of the candidate and a reference Job. This new property will be the compatibility between the Candidate and the requirements of the Job. In some cases I will need to find Candidates based on the compatibility property.

Thank you in advance.

like image 694
Nacorga Avatar asked Dec 27 '25 19:12

Nacorga


1 Answers

I think what you need is a pre hook on save, and in this case something like:

    CandidateSchema.pre('save', async function() {
      if(this.isModified('someothervalue'){
      const job = await JobSchema.find({'related job query'});
      this.compatibility = job.somevalue + this.someothervalue; //this is your current candidate
    }
    });

JobSchema.post('save', async function(job) {
      const candidates = await CandidateSchema.find({'related candidates query'});
      const candidateUpdates = [];
      candidates.forEach(candidate => {
          candidate.compatibility = job.somevalue + candidate.someothervalue; //this is your current candidate
          candidateUpdates.push(candidate.save());
    })
      await Promise.all(candidateUpdates);
    });

It may be a lot to process the above, but basically means that when you update a job, all related users ('related candidates query') get updated after a job is updated (normally you would need to check only if the fields that affect the users' compatibility are changed, but that's another thing), and the first hook just updates the user's compatibility when his fields that affect it are updated (like someothervalue).

like image 75
Ncifra Avatar answered Dec 30 '25 09:12

Ncifra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!