0

There is an existing collection1 having a property which is an id of another collection2 but the data type is string. How do I convert this property to an objectId type with reference to the other collection2.

Environment: "mongoose": "^8.6.1", node: 20.17.0


const candidateSchema = mongoose.Schema({
  fullName: { type: String, required: true },
  gender: { type: String },
  cvPath: { type: String },
  cvAddedOn: { type: Date },
  email: { type: String },
  area: { type: String },
  city: { type: String },
  state: { type: String },
  mobile1: { type: String },
  //....
})

module.exports = mongoose.model('Candidate', candidateSchema)



const shortlistSchema = mongoose.Schema({
  ourSrNo: { type: Number },
  candId: { type: String },  
    /// this should have been candidate: { type: mongoose.Schema.Types.ObjectId, ref: 'Candidate'},
    /// and the below candidate related fields should have been populated in query
  candSrNo: { type: Number },
  candName: { type: String },
  cvPath: { type: String },
  mobile1: { type: String },
  //....
})

module.exports = mongoose.model('Shortlist', shortlistSchema);

Required: change the existing Shortlist documents having candId property of type string into reference type property

Definitely I will have to change the shortlistSchema to add the below property

candidate: { type: mongoose.Schema.Types.ObjectId, ref: 'Candidate'},

Is the below script correct to update the existing data? Can it be improved by running one command instead of iterating in shortlist collection one by one?

  const shortlists = await Shortlist.find().select('candId').lean().exec();

  for(const s of shortlists){
    const shortlist = await Shortlist.findById(s._id);
    shortlist.candidate = new mongoose.Types.ObjectId(s.candId);
    
    /// delete unwanted old embedded properties
    delete shortlist.candSrNo;
    delete shortlist.candName
    delete shortlist.mobile1
    ///.....

    await shortlist.save();
  }

I do not want to mess up the existing data, hence need help.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.