【问题标题】:Why is `_id` not accepting by custom string using Mongoose?为什么`_id`不接受使用Mongoose的自定义字符串?
【发布时间】:2021-08-21 19:35:50
【问题描述】:

我正在尝试根据我在服务器中定义的topic 对象的标题创建一个_id 字段。这是架构。

const { gql } = require('apollo-server-express')

const typeDefs = gql`
    type Topic @key(fields: "name") {
        name: String,
        desc: String,
        body: String,
        subject: [String]
    }
`

然后是解析器

const resolvers = {
     Mutation: {
        addTopic(parent, args, context, info) {
            const { name, desc, body, subject } = args
            const topicObj = new Topic({
                _id: name,
                name,
                desc,
                body,
                subject
            })
            return topicObj.save()
                .then(result => {
                    return{ ...result._doc}
                })
                .catch(err => {
                    console.error(err)
                })
        }
    }
}

我得到的错误是Cast to ObjectId failed for value "MyTopic" (type string) at path "_id"

不足为奇,当我使用 _id: mongoose.Types.ObjectId(name) 手动投射时,我得到了 Argument passed in must be a single String of 12 bytes or a string of 24 hex characters 错误。

我一定是误会了,但this 的帖子让我相信我的第一种方法是正确的,所以我不知道该怎么做才能让它发挥作用。

我想我必须想办法告诉 Mongoose 不要尝试施放它,但我不确定我是否应该这样做。


猫鼬模型

const TopicSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    desc: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    subject: {
        type: [String],
        required: true
    }
})

【问题讨论】:

  • 您也可以发布您的 Mongoose 架构吗?
  • @ChristosPanagiotakopoulos 完成

标签: mongodb mongoose apollo-server


【解决方案1】:

由于您尚未在 Mongoose 架构中声明您的 _id,因此 Mongoose 默认为您的文档的 _id 类型为 ObjectId 类型,而不是导致错误的 String 类型。

要解决这个问题,您可以像这样在架构中声明 _id

const TopicSchema = new Schema({
    _id: String,
    name: {
        type: String,
        required: true
    },
    desc: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    subject: {
        type: [String],
        required: true
    }
})

您可以在这里阅读更多内容:How to set _id to db document in Mongoose?

【讨论】:

    猜你喜欢
    • 2019-03-12
    • 2015-03-25
    • 2013-12-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多