Mongoose: CastError: Cast to ObjectId failed for value “[object Object]” at path “_id”

前端 未结 13 2067
再見小時候
再見小時候 2020-11-30 01:24

I am new to node.js, so I have a feeling that this will be something silly that I have overlooked, but I haven\'t been able to find an answer that fixes my problem. What I\'

13条回答
  •  执笔经年
    2020-11-30 02:04

    For the record: I had this error trying to fill a subdocument in a wrong way:

    {
    [CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
    message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
    name: 'CastError',
    type: 'ObjectId',
    path: '_id'
    value:
      [ { timestamp: '2014-07-03T00:23:45-04:00',
      date_start: '2014-07-03T00:23:45-04:00',
      date_end: '2014-07-03T00:23:45-04:00',
      operation: 'Deactivation' } ],
    }
    

    look ^ value is an array containing an object: wrong!

    Explanation: I was sending data from php to a node.js API in this way:

    $history = json_encode(
    array(
      array(
      'timestamp'  => date('c', time()),
      'date_start' => date('c', time()),
      'date_end'   => date('c', time()),
      'operation'  => 'Deactivation'
    )));
    

    As you can see $history is an array containing an array. That's why mongoose try to fill _id (or any other field) with an array instead than a Scheme.ObjectId (or any other data type). The following works:

    $history = json_encode(
    array(
      'timestamp'  => date('c', time()),
      'date_start' => date('c', time()),
      'date_end'   => date('c', time()),
      'operation'  => 'Deactivation'
    ));
    

提交回复
热议问题