Reputation: 431
I recently started working with GraphQL. I am able fetch the records from mongodb collections with the base of name, but if I try the same code to get the data by _id(mongodb generated id) I am getting null values for all fields. Here is my sample code...
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
// To get a user based on id
getUser: {
type: UserType,
args: {
_id: {
description: 'The username of the user',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (root, {_id}) => {
//Connect to Mongo DB
return mongo()
.then(db => {
return new Promise(
function(resolve,reject){
//Query database
let collection = db.collection('users');
collection.findOne({ _id},(err,userData) => {
if (err) {
reject(err);
return;
}
console.log(userData);
resolve(userData);
});
})
});
}
},
and the sample query is:
{
getUser ( _id: "55dd6300d40f9d3810b7f656")
{
username,
email,
password
}
}
I am getting response like:
{
"data": {
"getUser": null
}
}
Please suggest me any modifications if required... Thanq.
Upvotes: 0
Views: 313
Reputation: 36
Because the "_id" field generated by mongoDB is not just a string, it is actually ObjectId("YOUR ID STRING HERE").
So in your query, mongoDB won't find any _id that is equal to the string you feed to it.
Try to use collection.findById() instead.
Upvotes: 2