Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method for carrying out CRUD operations on subdocuments in Mongoose is:

  1. Create: To create a subdocument, use the push() or unshift() method on the parent document's subdocument array with the new subdocument as an argument. For example:
const parentDoc = await ParentModel.findById(parentDocId);
const newSubdoc = { title: 'New Subdocument' };
parentDoc.subdocs.push(newSubdoc);
await parentDoc.save();
  1. Read: To read a subdocument, use the array index to access the desired subdocument. For example:
const parentDoc = await ParentModel.findById(parentDocId);
const subdoc = parentDoc.subdocs[index];
  1. Update: To update a subdocument, use the set() method to modify the subdocument and then call the parent document's save() method. For example:
const parentDoc = await ParentModel.findById(parentDocId);
parentDoc.subdocs[index].set({ title: 'Updated Subdocument' });
await parentDoc.save();
  1. Delete: To delete a subdocument, use the splice() method on the parent document's subdocument array with the array index and number of subdocuments to remove as arguments. For example:
const parentDoc = await ParentModel.findById(parentDocId);
parentDoc.subdocs.splice(index, 1);
await parentDoc.save();