0

An update in the array of objects inside another array of objects.

mongodb field that I'm working on:

otherFields: values,

tasks: [
 {
  _id: mongodb.objectID(),
  title: string,
  items:[{
   _id: mongodb.objectID(),
   title: string,
   completed: boolean        //field need to be update.
  }]
 },
 {}...
],

otherFields: value

sample mongodb document

I need to find the document using the task_id and the item_id and update a completed field in item of a task. Using the mongoose findOneAndUpdate method

const path = "tasks.$.items." + item_id + "completed";
collectionName.findOneAndUpdate( 
{ _id: req.user._id, "tasks._id": taskID }, 
{ $set: { [path]: true }}); 

The above query doesn't work!!!

Vicky
  • 1
  • 2
  • What have you tried so far? – eol Jun 07 '21 at 12:29
  • ``` const path = "tasks.$.items." + item_id + "completed"; collectionName.findOneAndUpdate( { _id: req.user._id, "tasks._id": taskID }, { $set: { [path]: true } } ); ``` This doesn't work! – Vicky Jun 08 '21 at 12:43
  • Please edit your question (https://stackoverflow.com/posts/67871554/edit) and add the code there. – eol Jun 08 '21 at 12:46

1 Answers1

0

There is no need to use multiple query conditions, since you'd like to update a specific item that has an unique ID. Therefore you could use something along the lines:

collectionName.findOneAndUpdate(
  { 'tasks.items._id': itemID },
  ...
);

Keep in mind this structure is far away from optimized as it would basically look through the entire database...


Also now that I think of it, you'd also have issue with the update, as there are two nested arrays within the document. Read more here: How to Update Multiple Array Elements in mongodb

Andrey Popov
  • 7,362
  • 4
  • 38
  • 58