financial_physician
financial_physician

Reputation: 1998

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

I'm trying to make an _id field based off the title for topic object I've defined in my server. Here's the the schema.

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

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

And then here's the resolver

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)
                })
        }
    }
}

The error that I'm getting is Cast to ObjectId failed for value "MyTopic" (type string) at path "_id".

Not too surprisingly, when I cast it manually with _id: mongoose.Types.ObjectId(name) I get the Argument passed in must be a single String of 12 bytes or a string of 24 hex characters error.

I must be misunderstanding, but this post lead me to believe my first approach is the right one so I'm not sure what to do to get it working.

I think I have to find some way to tell Mongoose not to try casting it but I'm not sure if that's what I should be doing.


Mongoose Model

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

Upvotes: 1

Views: 2880

Answers (1)

Because you haven't declared your _id on your Mongoose Schema, Mongoose is defaulting to an ObjectId type for your documents' _id instead of a String one that leads to the error.

To solve this you can declare the _id in your schema like this:

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
    }
})

You can read more here: How to set _id to db document in Mongoose?

Upvotes: 2

Related Questions