mongoose - 使用 $pull 删除数组中的元素

elm*_*mar 5 javascript mongoose mongodb node.js express

我有一个看起来像这样的节点对象:

{
   "_id":"58b336e105ac8eec70aef159",
   "name":"my node",
   "ip":"192.168.1.1",
   "__v":0,
   "configuration":{
       "links":[
         {
            "linkName":"athena_fw_listen_tcp_5555",
            "_id":"58b336e105ac8eec70aef15d",
            "local":true
         },
         {
            "linkName":"athena_fw_listen_udp_5554",
            "_id":"58b336e105ac8eec70aef15c",
            "local":true
         }
      ]
   }
}
Run Code Online (Sandbox Code Playgroud)

我正在向我的快速服务器发送一个删除请求,如下所示: DELETE http://localhost:9000/api/nodes/58b336e105ac8eec70aef159/links/58b336e105ac8eec70aef15d

我跟着指示$拉MongoDB的文档,我也试过这个

但它似乎不起作用,因为我不断收到: 500 (Internal Server Error)

这是我快递方面的代码的样子:

{
   "_id":"58b336e105ac8eec70aef159",
   "name":"my node",
   "ip":"192.168.1.1",
   "__v":0,
   "configuration":{
       "links":[
         {
            "linkName":"athena_fw_listen_tcp_5555",
            "_id":"58b336e105ac8eec70aef15d",
            "local":true
         },
         {
            "linkName":"athena_fw_listen_udp_5554",
            "_id":"58b336e105ac8eec70aef15c",
            "local":true
         }
      ]
   }
}
Run Code Online (Sandbox Code Playgroud)

快速路由器包含以下内容: router.delete('/:id/links/:linkId', controller.destroyLink);

所以我期待 id 和 linkId 作为参数,我使用 id ( _id: req.params.id) 来定位特定节点,使用 linkId ( _id: req.params.linkId) 来定位特定链接,但它不起作用!

需要帮助解决问题,我不知道我在这里遗漏了什么!

elm*_*mar 13

大家好,感谢您的帮助。我终于让它工作了!!!

经过近 3 个小时的故障排除 :'( :'( 这是使用的解决方案:

exports.destroyLink = function(req, res) {
Node.findByIdAndUpdate(
    req.params.id, { $pull: { "configuration.links": { _id: req.params.linkId } } }, { safe: true, upsert: true },
    function(err, node) {
        if (err) { return handleError(res, err); }
        return res.status(200).json(node.configuration.links);
    });
};
Run Code Online (Sandbox Code Playgroud)

findById我没有更新节点,而是使用findByIdAndUpdate. 它现在完美运行!!!

我仍然没有找到其他版本的解释。但无论如何很高兴它以这种方式工作。