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();
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
Asked: 2021-12-22 11:00:00 +0000
Seen: 13 times
Last updated: Dec 19 '22
Is it advisable to create event handlers in a separate method rather than inline all the time?
How can you create an OpenGL plot without relying on external libraries, starting from scratch?
How can I use iText7 to create a PDF that includes a pie chart?
How can I create a monitor in Datadog that includes multiple resources' metrics in one monitor?
Create a regular expression for the following format.
How to create GS1-128 using ZXing.Net?
How to implement a leaderboard in Flutter?
How to create a plot using mplfinance and PyQt5 that includes a volume graph?
What is a simple way to create a for loop in React that produces errors?