Remove sub-document from Mongo with mongoose

后端 未结 6 534
情歌与酒
情歌与酒 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:38

    You want inventory.items.pull(req.params.itemSku), followed by an inventory.save call. .remove is for top-level documents

    0 讨论(0)
  • 2020-12-16 01:38
        const deleteitem = (req, res) => {
        var id = req.body.id
        var iditem = req.body.iditem
    
        Venta.findOne({'_id': id}, function(err,result){
            if (err) {
                console.log(err);            
            }else{
                result.items.pull(iditem)
                result.save()
            }
        })}
    module.exports = {deleteitem }
    
    0 讨论(0)
  • 2020-12-16 01:44

    finaly!

    MongoDB:
    
    "imgs" : {"other" : [ {
            "crop" : "../uploads/584251f58148e3150fa5c1a7/photo_2016-11-09_21-38-55.jpg",
            "origin" : "../uploads/584251f58148e3150fa5c1a7/o-photo_2016-11-09_21-38-55.jpg",
            "_id" : ObjectId("58433bdcf75adf27cb1e8608")
                                        }
                                ]
                        },
    router.get('/obj/:id',  function(req, res) {
    var id = req.params.id;
    
    
    
    Model.findOne({'imgs.other._id': id}, function (err, result) {
            result.imgs.other.id(id).remove();
            result.save();            
        });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 01:54

    Subdocuments now have a remove function. Use as follows from the spec:

    var doc = parent.children.id(id).remove();
    parent.save(function (err) {
      if (err) return handleError(err);
      console.log('the sub-doc was removed')
    });
    
    0 讨论(0)
  • 2020-12-16 01:55

    You can simply use $pull to remove a sub-document.

        Collection.update({
        _id: parentDocumentId
      }, {
        $pull: {
          subDocument: {
            _id: SubDocumentId
          }
        }
      });
    

    This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.

    0 讨论(0)
提交回复
热议问题