【问题标题】:How to remove an element from an array included in an Object如何从对象中包含的数组中删除元素
【发布时间】:2019-07-12 04:55:58
【问题描述】:

我正在尝试使用 MongoDB 和 nodejs 构建一个应用程序。 我有一个模型Ride,其中包含一个名为steps 的用户ID 数组。我想从由其自己的 RideID 指定的 Ride 中删除一个 userID 条目。

我尝试了以下代码,但它不起作用,总是引发错误

router.post('/quitRide',async (req,res)=>{
    let userID = req.body.userID; //userID to be deleted
    let rideID = req.body.rideID; //rideID of the Ride we want to access

    Ride.find({_id:rideID})
    .exec()
    .then(t => {
      t[0].steps.splice(t[0].steps.indexOf(userID), 1);
      res.status(200);
    })
    .catch(err => res.status(400).json({error : err}))
  })

这是我得到的错误:

{错误:“erreurTypeError: 无法读取未定义的属性‘indexOf’”}

似乎无法访问步骤

【问题讨论】:

  • 在有问题的行前添加console.log( t[0] );(或使用调试器检查)。
  • 是否有没有steps 的游乐设施(可能是新创建的游乐设施?)

标签: node.js mongodb mongoose


【解决方案1】:

尝试使用$pull,更多信息请访问this link

router.post('/quitRide',async (req,res)=>{
    let userID = req.body.userID; // userID to be deleted
    let rideID = req.body.rideID; // rideID of the Ride we want to access

    Ride.findOneAndUpdate({_id:rideID}, { $pull: { steps: userId } })
    .exec()
    .then(t => {
      // response with success
      res.status(200);
    })
    .catch(err => res.status(400).json({error : err}))
  })

【讨论】:

    【解决方案2】:

    您可以使用 Lodash Remove 函数从数组中删除元素。 您可以通过运行此命令 npm i --save lodash.remove 来安装 npm 包,然后在您的代码中进行更改。

        router.post('/quitRide',async (req,res)=>{
            let userID = req.body.userID; //userID to be deleted
            let rideID = req.body.rideID; //rideID of the Ride we want to access
    
            Ride.find({_id:rideID})
            .exec()
            .then(t => {
              _.remove(t[0].steps,userID);
                console.log(t[0].steps)//which contains your array without userID
               res.status(200);
            })
            .catch(err => res.status(400).json({error : err}))
          })
    

    不要忘记导入/需要 lodash 包,您可以在下面的链接中找到文档

    https://lodash.com/docs/4.17.14#remove

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 2017-03-21
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多