To push an item to an array within a subdocument in Mongoose, you need to use the positional operator $
along with the findOneAndUpdate
or update
method. The positional operator allows you to update elements of an array in a subdocument without knowing their index.
Let's assume you have the following Mongoose schema with a subdocument array:
javascriptconst mongoose = require('mongoose');
const subdocumentSchema = new mongoose.Schema({
name: String,
items: [String],
});
const parentSchema = new mongoose.Schema({
subdocument: subdocumentSchema,
});
const ParentModel = mongoose.model('Parent', parentSchema);
To push an item to the items
array within the subdocument
, you can use the following code:
javascriptconst newItem = 'New Item';
ParentModel.findOneAndUpdate(
{ 'subdocument._id': subdocumentId }, // Match the parent document with the subdocument's _id
{ $push: { 'subdocument.items': newItem } }, // Use $push to add the newItem to the subdocument's items array
{ new: true } // Return the updated document
)
.then((updatedParent) => {
console.log(updatedParent);
})
.catch((error) => {
console.error(error);
});
In the above code:
subdocumentId
is the _id of the subdocument you want to update. Make sure you replace it with the actual _id value you want to target.- We use
findOneAndUpdate
to find the parent document that contains the subdocument with the specified_id
and update it. - The
$push
operator is used to push thenewItem
to theitems
array within the subdocument. - The option
{ new: true }
tells Mongoose to return the updated document after the update operation is complete.
After running this code, the newItem
will be added to the items
array within the specified subdocument, and the updated parent document will be logged to the console.