The method for carrying out CRUD operations on subdocuments in Mongoose is:
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();
const parentDoc = await ParentModel.findById(parentDocId);
const subdoc = parentDoc.subdocs[index];
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();
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();
Asked: 2021-12-22 11:00:00 +0000
Seen: 13 times
Last updated: Dec 19 '22