I have two tables, titles and members and I would like to reference id of title inside member.
My database structure looks like this:
// collection titles
{
"_id": ObjectId("5dd5brf45d1320b01edc1432"),
"name": "mother"
}
{
"_id": ObjectId("3dw5brf45t3320b01edc2864"),
"name": "wife"
}
// collection members
{
"_id": ObjectId("5rd7tjh23t5786k42edf9753"),
"firstName": "Mary",
"familyTitles": ["mother", "wife"]
}
But I would like to replace it to
// collection members
{
"_id": ObjectId("5rd7tjh23t5786k42edf9753"),
"firstName": "Mary",
"familyTitles": [ObjectId("5dd5brf45d1320b01edc1432"), ObjectId("3dw5brf45t3320b01edc2864")]
}
This is the script that I tried:
db.members.find({}).forEach((member) => {
member.familyTitles.forEach((familyTitle, i) => {
var titleId = db.titles.findOne({name: familyTitle});
member.familyTitles[i].update({$set: {i: titleId._id}})
})
})
But I get the following error: TypeError: member.familyTitles is undefined.
--- EDIT 1 ---
I tried to modify my script as follows:
var members = db.members.find({});
if (members) {
members.forEach((member) => {
if (member.familyTitles) {
member.familyTitles.forEach((familyTitle, i) => {
if (familyTitle) {
var titleId = db.titles.findOne({name: familyTitle});
db.members.update({_id: member._id}, {$set: {"familyTitles.$": titleId._id}});
}
}
})
}
})
}
It runs it but it without errors but it doesn't make any changes.
find()andfindOne()is async so you need to await it.