admin管理员组文章数量:1402995
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.
本文标签: nodejsHow do I change existing string type property into reference type propertyStack Overflow
版权声明:本文标题:node.js - How do I change existing string type property into reference type property? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744368774a2602915.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论