0

I have document named Category and subdocument with an array as Items. When I remove the subdocument, I am unable to confirm either it is deleted or not. Either the provided subdocument id was correct or not.

If I provide invalid item id (not available in database), it does not give me an error or some clue.

Code Modified

router.delete('/:category/:item', async (req, res) => {

        let categoryId: number = req.params.category;
        let itemId: number = req.params.item;

        CategorySchema.findOneAndUpdate(
            { category_id: categoryId },
            { $pull: { items: { item_id: itemId } } },
            { new: true }, function(err, doc, raw) {
            console.log(raw) // undefined
        });

        res.status(200).send(itemId);
})

Please help to improve!!!

Regards

MWN
  • 377
  • 1
  • 5
  • 17
  • You can set the `rawResult` option which will return the response showing if the document was "modified" or not. See also [`findOnAndUpdate()`](http://mongoosejs.com/docs/api.html#findoneandupdate_findOneAndUpdate) for this and other options settings. – Neil Lunn May 29 '18 at 06:22
  • alright, can you show me how to use `rawResult` in `async & await` – MWN May 29 '18 at 06:30
  • You can look at the existing answers and simply add the option to the command. `async/await` is simply "sugar" for promies. The same code with `then()` or even callbacks still applies, so there does not need to be new answers just because you want to `await Model.findOne...` rather than `Model.findOne...(...,function(err,doc) {...` It's all the same thing. – Neil Lunn May 29 '18 at 06:32
  • getting `rawResult` undefined – MWN May 29 '18 at 07:16

0 Answers0