14

我正在尝试从存储在猫鼬文档中的集合中删除一个项目。我的文档如下所示:

{
  "__v": 3,
  "_id": "5221040475f174d59a000005",
  "items": [
    {
      "sku": 1321654654613213,
      "name": "goldfish",
      "quantity": 12,
      "_id": "52224ed5bd9d340000000003"
    },
    {
      "sku": 12,
      "name": "goldfish",
      "quantity": 13,
      "_id": "52225dcbf2f1e40000000003"
    },
    {
      "sku": 1299,
      "name": "goldfish",
      "quantity": 13,
      "_id": "522260b6f2f1e40000000004"
    }
  ]
}

我想删除 sku 为 12 的金鱼。我正在执行以下操作:

var inventory = res.locals.content;
inventory.items.remove( {sku: req.params.itemSku}, function (err, item) {
  if (err) {
    console.log('error occurred', err);
    res.send('error');
  }
  else {
    res.send('Item found and deleted');
    return; 
  }
});

当我这样做时,我收到错误“TypeError:无法读取未定义的属性'等于'”。我不明白为什么。

4

7 回答 7

31

子文档现在具有删除功能。从规范中使用如下:

var doc = parent.children.id(id).remove();
parent.save(function (err) {
  if (err) return handleError(err);
  console.log('the sub-doc was removed')
});
于 2014-04-23T21:21:56.667 回答
17

你想要inventory.items.pull(req.params.itemSku),然后inventory.save打电话。.remove用于顶级文档

于 2013-09-01T06:09:31.207 回答
8

从数组中删除子文档

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.

于 2019-06-08T21:31:52.903 回答
7

最后!

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();            
    });
于 2016-12-04T01:37:50.287 回答
2

您可以简单地使用$pull删除子文档。

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

这将根据给定的 ID 找到您的父文档,然后从子文档中删除与给定条件匹配的元素。

于 2018-08-23T09:15:28.327 回答
1
    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 }
于 2020-05-04T19:16:29.767 回答
0

You don't need the parent's _id. You can just search for a parent which has a child with a specific id and pull that same child out with the following code:

const result = await User.updateOne(
  // Query the user collection for a document
  // with a child in it's accounts array with an _id of ChildAccountId.
  { 'accounts._id': 'ChildAccountId' },
  {
    // In the found parent document:
    $pull: { // pull something out of:
      accounts: { // the accounts array 
        _id: 'ChildAccountId' // which has has the _id of ChildAccountId.
      }
    }
  }
);

result in this case will have a response-object similar to the following one:

{
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

So you can easily check for the result.modifiedCount to see how many SubDocuments (in this case) were modified (where stuff got pulled out).

于 2022-02-23T16:25:57.083 回答