1

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

1 Answer 1

2

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.