bevc
bevc

Reputation: 203

Mongoose findOneAndUpdate an array within an array within a document

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?

Upvotes: 0

Views: 1160

Answers (1)

Joshua Oweipadei
Joshua Oweipadei

Reputation: 167

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

Upvotes: 1

Related Questions