I am using GraphQL MongoDB Mongoose together and I have 2 collections .. users and categories like below.
Category.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = new mongoose.Schema({
title:{
type: String,
required: true
},
userid: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
});
module.exports = mongoose.model('Category',categorySchema);
`
User.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
}
});
module.exports = mongoose.model('User',userSchema);
Resolver.js
const User = require('../models/User');
const Category = require('../models/Category');
const resolvers = {
getUsers: async () => {
try {
const users = await User.find().populate('categories');
return users;
} catch(err){
throw new Error(err);
}
},
};
module.exports = resolvers;
As you can see .. I have 2 collections . and inside Categories collection.. I am adding my data with userid .. everything is working fine .. But I am unable to get categories as its keep showing null in response.
Here below is my GraphQL query.
query{
getUsers{
id,
name
}
}
And here is what I get in response evenif I have data with userid same from users collection.
{
"data": {
"getUsers": [
{
"id": "65d316bdab8179475bdb0fef",
"name": "mittul",
}
]
}
}
UPDATE ..
Getting this response.
{
"data": {
"getUsers": null
}
}
try {
var resources = {};
const users = await User.aggregate([{
$group : {_id : null, totalPop: { $sum: "$pop" }}
},{
$lookup: {
from: "Category", // from collection name
localField: "userid",
foreignField: "_id",
as: "categories"
}
}]);
console.log(users);
} catch(err){
console.log(err);
throw new Error(err);
}
I have also tried below code but its giving me null in response and nothing in console.log.
User.find().populate("categories")
.then(users => {
console.log(users);
//res.send(users);
}).catch(err => {
throw new Error(err);
});
Below are my 2 collections.
Can anyone guide me what I am missing here ?
Thanks


ObjectIdas the value to theUser.categoriesproperty which corresponds to a matchingCategory._id?populatemethod takes anObjectIdand uses this to do a$lookupinto another collection to find a document that has an_idvalue equal to the referencedObjectId. You need to manually add thisObjectidinto the parent document in order forpopulateto work. If there is noObjectidgiven for eachUser.categorieshow do you expect mongoose to find the referencedCategorydocument from thecategoriescollection?populate?$lookupand you will still need to store an identifier in one of the documents in order to match one document with the other. I don't know how you expect to make the relationship otherwise? MongoDB allows you store one document directly inside another document so that you don't need topopulate. You should read about subdocuments.