使用mongoose从Mongo中删除子文档

Bra*_*don 8 mongoose node.js

我试图从存储在猫鼬文档中的集合中删除一个项目.我的文档看起来像这样:

{
  "__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"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想用12的sku去掉金鱼.我正在做以下事情:

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; 
  }
});
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lex 27

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

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

  • @OllyBarca我确实做到了,因此"从规范中使用如下". (6认同)
  • 你直接从mongoose的乏味文档中复制了这些内容 (4认同)

Pet*_*ons 13

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

  • `pull`返回`this`,可能是为了可链接性,所以你可以做`inventory.items.pull(blah).push(blah)`.https://github.com/LearnBoost/mongoose/blob/c328227a21004c7c1a295d215bbe55801e29c9ea/lib/types/array.js#L470 (3认同)

rob*_*nix 7

从数组中删除子文档

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

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

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


小智 5

最后!

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();            
    });
Run Code Online (Sandbox Code Playgroud)