Remove sub-document from Mongo with mongoose

后端 未结 6 551
情歌与酒
情歌与酒 2020-12-16 01:12

I am trying to remove an item from a collection that is stored in a mongoose document. My document looks like this:

{
  \"__v\": 3,
  \"_id\": \"5221040475f         


        
6条回答
  •  不知归路
    2020-12-16 01:49

    Removing a subdocument from an array

    The nicest and most complete solution I have found that both finds and removes a subdocument from an array is using Mongoose's $pull method:

    Collection.findOneAndUpdate(
        { _id: yourCollectionId },
        { $pull: { subdocumentsArray: { _id: subdocumentId} } },
        { new: true },
        function(err) {
            if (err) { console.log(err) }
        }
    )
    

    The {new: true} ensures the updated version of the data is returned, rather than the old data.

提交回复
热议问题