【问题标题】:Delete an item in array within an array删除数组中数组中的一项
【发布时间】:2020-07-30 22:09:43
【问题描述】:

我是否在后端 API 中正确执行此操作?您将如何删除后端父数组中的数组内的对象?我首先找到了主父数组索引,然后我使用 .tasks[index] 从任务数组中找到了对象。问题是如何在节点中删除它?我发现的教程使用 req.params.id 删除项目,但我的更复杂。

    exports.deleteTaskItem = async (req, res) => {
      const taskindex = req.params.id;
      const index = req.params.index;
      try {
        const taskfound = await Task.findById(taskindex);
        const taskfounditem = await taskfound.tasks[index];
//code to type here
        res.status(204).json({
          status: "success",
          data: null
        });
      } catch (err) {
        res.status(404).json({
          status: "fail",
          message: err
        });
      }
    };

【问题讨论】:

    标签: node.js express mongoose axios


    【解决方案1】:

    我相信您会对以下文档感兴趣: https://docs.mongodb.com/manual/reference/operator/update-array/

    并且要指定,我相信您想使用 $pull 运算符。

    类似这样的:

    const {id, index} = req.params;
    await Task.findByIdAndUpdate(id,{
        $pull: {
            tasks: { _id: index }
        }
    });
    

    (免责声明:对不起,我这次没有对此进行测试。但它应该很接近。)

    编辑:现在当我重新阅读问题时,我注意到您想使用索引。就我个人而言,我认为添加 id 会更容易,因为如果您使用子文档,您会自动获得它。但是如果您坚持使用索引,也许这个答案会有所帮助:

    https://stackoverflow.com/a/4970050/1497533

    再次编辑: 看来这有助于获得一个可行的解决方案,所以我将从 cmets 复制它:

    taskfound.tasks.splice(taskindex, 1); 
    taskfound.markModified('tasks'); 
    await taskfound.save();
    

    【讨论】:

    • taskfound 和 taskfounditem 都返回数组中的正确元素。我尝试了以下代码,但没有成功: await Task.update( { _id: ObjectId(taskindex) }, { $pull: { tasks: [index] } } );我也试过 $pull: {tasks: index} 但结果相同。
    • 好吧,如果你想用更多的步骤来做。 taskfound.tasks.splice(taskindex, 1); taskfound.markModified('tasks'); await taskfound.save();
    • 您的解决方案奏效了! taskfound.tasks.splice(taskindex, 1); taskfound.markModified('tasks');等待 taskfound.save();非常感谢。我爱这个社区的人们,尤其是你 ippi。
    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2019-08-22
    • 2013-11-01
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多