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:

const 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:

const 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:

  1. 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.
  2. We use findOneAndUpdate to find the parent document that contains the subdocument with the specified _id and update it.
  3. The $push operator is used to push the newItem to the items array within the subdocument.
  4. 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.

Have questions or queries?
Get in Touch