1
votes

How to perform findOneAndDelete() method to nested objectId in mongoose. here is my Schema:

...
var favoriteSchema = new Schema(
  {
    dishes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Dish',
        unique: true,
      },
    ],
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  }
);
...

And here is a sample document:

{
    "dishes": [
        {
            ...
            "_id": "5ec7b32a793648289c8ad28c",
            "comments": [],
        }
    ],
    "_id": "5ec7dc88c4495c3ad44f32db",
    "user": {
        "_id": "5ec644d06715633270d0414d",
        "username": "falamiw",
    },
    ...
}

And in my /favorites/:dishId endpoint I want to query the document using the dishId params and if obtain then delete the document from the collection. But How to use findOneAndDelete({?:req.params.dishId}) ?

1

1 Answers

1
votes

What You want to achieve is called $pull

Based on Your schema it’s will be:

await Favourite.findOneAndUpdate(
  {"user": userId}, 
  {$pull: 
    {
      "dishes": req.params.deleteUid
    }
  });