0

I'm trying to update an array that sits inside another array in a document. The schema is like this:

const projectSchema = new mongoose.Schema({
stakeholders: [{
    stakeholderTitle: {
        type: String,
    },
   ...
   subgroup: [{
        subgroupTitle: {
            type: String
        },
        subgroupPercent: {
            type: Number,
        }
    }]
}],

and I'm trying to update the 'subgroup' array. I have got the query to work on its parent (the stakeholder array) with the positional $ operator, using the answer to this question I asked previously. So my query looks like this.....

await db.findOneAndUpdate({ find by the id }, { "stakeholders.$.stakeholderTitle": req.body.stakeholderTitle, ... "stakeholders.$.subgroup": req.body.subgroup })

However, this query doesn't work for the 'stakeholders subgroup' array, and makes it null. Looking through the mongo docs for the positional operator it states that 'The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value', which I guess might be my problem.

So how can I do this with a findOneAndUpdate query?

1 Answer 1

1

From what I see is you have to specify the object you want to update inside the subgroup array. Try this - (i.e I'm updating the subgroupTitle of the subgroup array);

await db.findOneAndUpdate(
  {
      _id: userId,
      "stakeholders.stakeholderTitle": req.body.stakeholderTitle,
      "stakeholders.stakeholderTitle.subgroup.subgroupTitle": req.body.subgroupTitle
  },
  {$set: {
      "stakeholders.stakeholderTitle.subgroup.$.subgroupPercent": somePercentValue,
      }
  },
);

Also note, it's only the array that you find that you can update. It might not be exactly what you want, but its a step closer

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

Comments

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.