javascript 获取错误节点BSONTypeError:传入的参数必须是12个字节的字符串、24个十六进制字符的字符串或整数值:Array

jei2mxaa  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(196)

我正在处理一个node js项目,在那里我得到了以下错误:

CastError: Cast to ObjectId failed for value "[ [ '63e8e6e8b8a285d68b1fbd0c', '63e9951ded54221a516fc622' ] ]" (type Array) at path "labels" because of "BSONTypeError"
    at ObjectId.cast (/var/www/html/IssueTracker/node_modules/mongoose/lib/schema/objectid.js:248:11)
    at ObjectId.SchemaType.applySetters (/var/www/html/IssueTracker/node_modules/mongoose/lib/schematype.js:1201:12)
    at Proxy._cast (/var/www/html/IssueTracker/node_modules/mongoose/lib/types/array/methods/index.js:245:43)
    at Proxy._mapCast (/var/www/html/IssueTracker/node_modules/mongoose/lib/types/array/methods/index.js:258:17)
    at Arguments.map (<anonymous>)
    at Proxy.push (/var/www/html/IssueTracker/node_modules/mongoose/lib/types/array/methods/index.js:675:21)
    at module.exports.createissue (/var/www/html/IssueTracker/controllers/issuecontroller/issuecontroller.js:121:27)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  stringValue: `"[ [ '63e8e6e8b8a285d68b1fbd0c', '63e9951ded54221a516fc622' ] ]"`,
  messageFormat: undefined,
  kind: 'ObjectId',
  value: [ [ '63e8e6e8b8a285d68b1fbd0c', '63e9951ded54221a516fc622' ] ],
  path: 'labels',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
      at new BSONTypeError (/var/www/html/IssueTracker/node_modules/bson/lib/error.js:41:28)
      at new ObjectId (/var/www/html/IssueTracker/node_modules/bson/lib/objectid.js:67:23)
      at castObjectId (/var/www/html/IssueTracker/node_modules/mongoose/lib/cast/objectid.js:25:12)
      at ObjectId.cast (/var/www/html/IssueTracker/node_modules/mongoose/lib/schema/objectid.js:246:12)
      at ObjectId.SchemaType.applySetters (/var/www/html/IssueTracker/node_modules/mongoose/lib/schematype.js:1201:12)
      at Proxy._cast (/var/www/html/IssueTracker/node_modules/mongoose/lib/types/array/methods/index.js:245:43)
      at Proxy._mapCast (/var/www/html/IssueTracker/node_modules/mongoose/lib/types/array/methods/index.js:258:17)
      at Arguments.map (<anonymous>)
      at Proxy.push (/var/www/html/IssueTracker/node_modules/mongoose/lib/types/array/methods/index.js:675:21)
      at module.exports.createissue (/var/www/html/IssueTracker/controllers/issuecontroller/issuecontroller.js:121:27),
  valueType: 'Array'
}

我有两个文档,一个是问题,另一个是标签。问题与标签模式有一对多的关系。因此,我的标签模式如下所示

labels:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Label'
    }],

问题是,当我使用此代码在标签中插入单个值时,不会收到错误

issues.labels.push(allLabelsWithId);

这里allLabelsWithId是一个数组。但是当这个数组的值大于1时,它会失败并给予上面提到的错误。
我需要传递多个值,那么正确的方法是什么呢?

kmpatx3s

kmpatx3s1#

尝试:

issues.labels.push(...allLabelsWithId);
rbpvctlc

rbpvctlc2#

对于多个值,$each运算符是一种解决方案

Issue.findByIdAndUpdate(yourId, {
  $push: { labels: { $each: allLabelsWithId } },
});

相关问题