What is the correct type to use for an ObjectId field across mongoose and GraphQL?
I didn't find an issue and ran this code with one of my existing code bases. Except I wrapped the mutation in the GraphQLObjectType
.
const Mutation = new GraphQLObjectType({ name: 'Mutation', fields: { addAccount: { type: AccountType, description: 'Create new account', args: { name: { name: 'Account Name', type: new GraphQLNonNull(GraphQLString) } }, resolve: (root, args) => { const newAccount = new Account({ name: args.name }); newAccount.id = newAccount._id; return new Promise((resolve, reject) => { newAccount.save(err => { if (err) reject(err); else resolve(newAccount); }); }); } } });
To get the working example: Clone the repo. In this repo, the app uses v0.13.2
and you are using v14.0.2
installed via npm i graphql
. Downgrade graphql
to v0.13.2
.
I used ID
and it works fine! cause of your problem is not id's type! it's becuase you provide it with wrong value: ObjectID('actuall id')
In order to fix this issue, call toJson
function for each fetched data, or simply add a virtual id
like this:
YourSchema.virtual('id').get(function() { return this.toJSON()._id}
So what I just found is that _id
is of type ObjectID
but seems to implicitly cast to String
. So if you define your mongoose model id type to be String
instead of mongoose.Schema.Types.ObjectId
then it should work. Using your current code (from the compose.com tutorial) that copies _id to id, the result will be that, in Mongo (after saving), the _id will be of type ObjectID
and your model id will be of type string.
In other words, instead of this
const Account = mongoose.model('Account', new mongoose.Schema({ id: mongoose.Schema.Types.ObjectId, name: String}));
Do this
const Account = mongoose.model('Account', new mongoose.Schema({ id: String, name: String}));