Ask Your Question
0

What is the method for carrying out Create, Read, Update, and Delete operations on subdocuments in Mongoose?

asked 2021-12-22 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-12-19 10:00:00 +0000

ladyg gravatar image

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();
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-22 11:00:00 +0000

Seen: 13 times

Last updated: Dec 19 '22