【问题标题】:Schema relations: Argument passed in must be a single String of 12 bytes or a string of 24 hex charactersSchema 关系:传入的参数必须是 12 个字节的单个字符串或 24 个十六进制字符的字符串
【发布时间】:2020-09-01 12:40:18
【问题描述】:

所以我正在尝试与猫鼬建立一些关系。但是当谈到将一个模式保存到另一个模式时,我得到了这个错误:

Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

这里有一些类似的模式:

mongoose = require('mongoose')
const Schema = mongoose.Schema

const userSchema = new Schema({
    _id: String,
    role: {
        type: String,
        default: 'Player'
    },
    tags: {
        type: [Schema.Types.ObjectId],
        ref: 'Tag'
    }
})

module.exports = mongoose.model('User', userSchema)
mongoose = require('mongoose')
const Schema = mongoose.Schema

const tagSchema = new Schema({
    _id: {
        type: String,
        require: true
    },
    description: {
        type: String,
        require: true
    },
    color: {
        type: String,
        default: '#2476d1'
    }
})

module.exports = mongoose.model('Tag', tagSchema)

以及我如何尝试链接

try {
    const tag = await Tag.findOne({_id: 'Noob'})

    user.tags.push(tag.id)
    await user.save()
} catch (err) {
    console.error(`ERROR: ${user._id} at Noob check`)
    console.error(err)
}

根据其他帖子,我也尝试过像这样推送_id

user.tags.push(mongoose.ObjectID(tag._id))
// and
user.tags.push(mongoose.ObjectID.createFromHexString('4e6f6f62')) // just 'Noob' in hex

我仍然得到那个错误。如何使用自定义 _id 创建引用?

【问题讨论】:

    标签: node.js mongodb mongoose schema


    【解决方案1】:

    你只是类型不匹配,ObjectId 对 Mongo 有一定的结构限制。字符串4e6f6f62 不符合这些限制。

    只需将您的用户架构 tags 字段更改为字符串:

    tags: {
            type: String,
            ref: 'Tag'
        }
    

    并且保持原样创建而不尝试将字符串转换为ObjectId。如果出于某种原因,您希望它为 ObjectId,则必须重新保存标签集合并将 _id 转换为有效的 ObjectId 格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      相关资源
      最近更新 更多