为什么 `_id` 不接受使用 Mongoose 的自定义字符串?

Why is `_id` not accepting by custom string using Mongoose?

我正在尝试根据我在服务器中定义的 topic object 的标题创建一个 _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 post 让我相信我的第一种方法是正确的,所以我不确定该怎么做才能让它发挥作用。

我想我必须找到一些方法告诉 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 Schema 上声明您的 _id,Mongoose 默认为您文档的 ObjectId 类型 _id 而不是 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?