'Delete object from inner schema in mongoose?

How do I delete object from inner schema in mongoose? I try to delete comments from the Holiday Schema, this is the holiday schema:

const holidaySchema = new mongoose.Schema(
  {
    comments: [commentSchema],
  },
)
const Holiday = mongoose.model("Holiday", holidaySchema);


export default Holiday;

and this is the comments schema:


const commentSchema = new mongoose.Schema(
  {
    action: { type: String },

    time: { type: String },

    name: { type: String },
    image: { type: String },

    content: { type: String },
    rating: { type: Number },
  },
  {
    timestamps: true,
  }
);


I try to delete a specific comment from the holidaySchema in this way:

holidayRouter.delete(
  "/:id/comments/:commentId",
  isAuth,
  expressAsyncHandler(async (req, res) => {
    const holiday = await Holiday.updateOne(
      { _id: req.params.id },
      { $pull: { comments: { _id: req.params.commentId } } }
    );
if(holiday){
  console.log(holiday);
}
  })
);


the console:

enter image description here

and this is not working, do you know what I am doing wrong or what should I do?

thank you



Solution 1:[1]

Mongoose converts the object into json, and we can customize that json which is returned.

 commentSchema.methods.toJSON = function(){
      const commentSchema = this.toObject()
    
      delete commentSchema.name
      delete commentSchema.rating
      
      return commentSchema 
    }

New the JSON which is returned will not have name and rating.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Infinity