【问题标题】:Inserting multiple ObjectIds to sub-document at once with mongoose使用 mongoose 一次将多个 ObjectId 插入子文档
【发布时间】:2020-12-26 23:53:23
【问题描述】:

我正在使用猫鼬,我有以下型号:

const UniversitySchema = new Schema({
    name: {
        type: String,
        required: [true, 'Name is required']
    },
    color: {
        type: String
    },
    paths: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Path'
    }]
})

我希望能够在第一次创建它时将多个路径(转换为路径模型)插入到大学集合中。我尝试了以下代码:

const newUni = new University({
    name: name,
    paths: [...pathIds],
    color: color
})

newUni.save()
    .then(uni => {
            return res.send(uni)
        })
    .catch(err => console.log(err)); 
    }) 

但它会引发此错误:

CastError: Cast to ObjectId failed for value "[ 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ]" at path "_id" for model "Path"

 messageFormat: undefined,
  stringValue: '"[ 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ]"',
  kind: 'ObjectId',
  value: [ 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ],
  path: '_id',
  reason: Error: Argument passed in must be a single String of 12 bytes or a string 
of 24 hex characters

看起来mongoose在有多个ID时不会单独投射ID,因为当我尝试使用一个ID时,它起作用了。

我也尝试过保存文档,然后将 ids 推送到路径数组,但没有成功。

有没有办法一次性完成?

提前致谢。

【问题讨论】:

    标签: javascript node.js express mongoose nosql


    【解决方案1】:

    您需要确保每个数组的id- 值中没有空格:

    使用此代码

    const newUni = new University({
        name,
        paths: ["5f122f9967c59932b44214b6","5f2762858f9060327c4f6b2f"],
        color
    })
    

    它肯定可以工作。

    所以假设pathIds最初持有字符串" 5f122f9967c59932b44214b6, 5f2762858f9060327c4f6b2f ",你可以简单地做

    ...
    paths: pathIds.split(",").map(v => v.trim()),
    ...
    

    获取修剪后的id-values 数组:

    【讨论】:

      猜你喜欢
      • 2015-05-30
      • 2016-12-14
      • 2014-09-11
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2021-01-10
      • 2011-09-01
      • 2018-06-11
      相关资源
      最近更新 更多