【问题标题】:CastError: Cast to ObjectId failed for value 'xxx' at path "_id"CastError:路径“_id”处的值“xxx”转换为 ObjectId 失败
【发布时间】:2020-05-20 01:20:35
【问题描述】:

我在请求中有一个数组:

{
"acceptedBookings": [
    {
        "id": "e1f66d7a852986709f665c3",
        "Date": "2020-02-04T05:03:25.332Z"
    }
  ]
}

我想更新每个“id”的“日期”。但是,如果我搜索为

await Booking.findById( acceptedBookings[0].id )

await Booking.findOne({_id : acceptedBookings[0].id})

没有回应

【问题讨论】:

    标签: arrays json mongoose


    【解决方案1】:

    您访问了错误的成员,您想要的是: 假设您的 map 类似于

      const acceptedBookings = {
      "accepted": [{
              "id": "e1f66d7a852986709f665c3",
              "Date": "2020-02-04T05:03:25.332Z"
          },
          {
              "id": "i123",
              "Date": "2020-02-04T05:03:25.332Z"
          },
          {
              "id": "i123",
              "Date": "2020-02-04T05:03:25.332Z"
          }
      ]
    };
    
    console.log(acceptedBookings.accepted[0].id); // e1f66d7a852986709f665c3
    console.log(acceptedBookings.accepted[1].id); // i123
    
    await Booking.findById( acceptedBookings.accepted[0].id ) //should work fine
    

    记住您创建的对象不是array,而是map/objectkey: value 对 因此首先获得正确的数组/元素然后访问它的成员

    【讨论】:

    • Booking.findOne()方法的代码更新你的问题
    猜你喜欢
    • 2016-11-11
    • 2014-06-20
    • 2021-02-21
    • 2017-03-26
    • 2017-05-26
    • 2019-01-06
    • 2016-05-06
    • 2018-03-17
    • 2015-07-16
    相关资源
    最近更新 更多