0

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.

1
  • find() and findOne() is async so you need to await it. Commented Oct 22, 2019 at 2:29

1 Answer 1

2

Try this way

 db.titles.findOne({name: familyTitle}).then(title => {
        db.members.update({_id: member._id,familyTitles:title.name }, {$set: {"familyTitles.$": title._id}});
  }

findOne - this is async method so you can get the result by using then method or you can use await(async_await.js) operator to get the result once the operation is completed.

familyTitles:title.name - you must specify the exact matching value for the array values in the query to update.

Referral links:

mongodb-javascript

Update Values in an Array (<array>.$)

Sign up to request clarification or add additional context in comments.

1 Comment

I tried but it didn't work. What I ended up doing was creating a new array, push the values inside and then replace the whole value of familyTitles with the new array that contained ids.

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.