繁体   English   中英

使用 mongoose 从 Mongo 中删除子文档

[英]Remove sub-document from Mongo with mongoose

我正在尝试从存储在 mongoose 文档中的集合中删除一个项目。 我的文件看起来像这样:

{
  "__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; 
  }
});

当我这样做时,出现错误“类型错误:无法读取未定义的属性‘等于’”。 我不明白为什么。

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

var doc = parent.children.id(id).remove();
parent.save(function (err) {
  if (err) return handleError(err);
  console.log('the sub-doc was removed')
});

您需要inventory.items.pull(req.params.itemSku) ,然后是一个inventory.save调用。 .remove用于顶级文档

终于!

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();            
    });

从数组中删除子文档

我发现从数组中查找和删除子文档的最好和最完整的解决方案是使用 Mongoose 的$pull方法:

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

{new: true}确保返回数据的更新版本,而不是旧数据。

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

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

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

    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 }

您不需要父母的 _id。 您可以只搜索具有特定 id 的孩子的父母,并使用以下代码将同一个孩子拉出来:

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将具有类似于以下的响应对象:

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

因此,您可以轻松地检查result.modifiedCount以查看有多少SubDocuments (在本例中)被修改(从哪里提取内容)。

笔记 -

来自 mongoose 6.3.1文档-

使用回调 function 执行查询时,您将查询指定为 JSON 文档。 JSON 文档的语法与 MongoDB shell 相同。

.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM