The GraphQL MongoDB integration with Mongoose is experiencing an issue where the populate field is not

I have implemented GraphQL MongoDB Mongoose in my project, where I have defined 2 collections - users and categories.

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;

Having set up these collections, I am facing an issue. Even though the data is present in the Categories collection with a valid userid, when querying to get categories, it returns null in the response.

Below is my GraphQL query:

query{
  getUsers{
    id,
    name
  }
}

The response I receive does not show the categories even though there are matching ids from the users collection.

{
  "data": {
    "getUsers": [
      {
        "id": "65d316bdab8179475bdb0fef",
        "name": "mittul"
        
      }
    ]
  }
}

UPDATE ..

When trying a different method for querying, I still get a null 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);            
        }

Furthermore, the code snippet provided below also gives me a null response without any output in the console log.

  User.find().populate("categories")
        .then(users => {
            console.log(users);
            //res.send(users);
        }).catch(err => {
                    
            throw new Error(err);            
        });

Attached are the screenshots of my 2 collections. Can anyone assist me in identifying the missing piece?

https://i.stack.imgur.com/lKPBH.png

https://i.stack.imgur.com/WW3FO.png

Thank you!

Answer №1

Check out this straightforward aggregation method for querying the users collection. In this instance, a $match is specified for the user.name property, but feel free to customize the query for any desired information within the users collection.

Following that, utilize a $lookup to delve into the categories collection and identify any Category entries with a matching userid value equal to the _id of the corresponding User from the initial users search.

The $set phase examines the returned categories array from the $lookup. If it's empty, the array will be removed; otherwise, it will remain intact.

const users = await User.aggregate([
  {
    $match: {
      _id: ObjectId("5a934e000102030405000001"),
      name: "mittul"
    }
  },
  {
    $lookup: {
      from: "categories",
      localField: "_id",
      foreignField: "userid",
      as: "categories"
    }
  },
  {
    $set: {
      "categories": {
        $cond: {
          if: {
            $eq: [
              "$categories",
              []
            ]
          },
          then: "$$REMOVE",
          else: "$categories"
        }
      }
    }
  }
])

For a live demonstration, visit HERE.

Answer №2

Hey everyone, I wanted to share with you my solution for updating an aggregate query.

getUsers: async (req,res) => {

       try {
            const users = await User.aggregate([
                {
                    $match: {
                        _id: { $ne: null } // Filtering out documents with null _id
                    }
                },
                {
                    $lookup: {
                        from: "categories",
                        localField: "_id",
                        foreignField: "userid",
                        as: "categories"
                    }
                },
                {
                    $addFields: {
                        "id": { $toString: "$_id" }, // Converting _id to string and assigning it to id
                        "categories": {
                            $map: {
                                input: "$categories",
                                as: "category",
                                in: {
                                    id: { $toString: "$$category._id" }, // Converting category's _id to string and assigning it to id
                                    title: "$$category.title"
                                }
                            }
                        }
                    }
                }
            ]);
            return users;
         } catch(err){
            throw new Error("Error retrieving user");            
        }

This approach works perfectly whether or not id is added for users or categories.

query{
  getUsers{
    
    id,name,email,categories{
      id,
      title
    }
      
  }
}

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up grunt-ts to function seamlessly with LiveReload

I am currently experimenting with using TypeScript within a Yeoman and Grunt setup. I've been utilizing a Grunt plugin called grunt-ts to compile my TypeScript files, and while the compilation process is smooth, I'm encountering issues with live ...

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...

Switching out built-in functions with testdouble.js?

Is it feasible to substitute an internal function in a node.js module with td.replace while using testdouble.js for testing? The internal function involves a DB call, so I prefer not to test it. However, I do want to verify that this function receives the ...

Unable to resolve this stubborn NPM/Node error plaguing my project

Currently, I am facing an issue while trying to install packages for a bot on my Ubuntu 16.04 server using npm 5 and Node.js 8. The problem seems to be related to sodium/libsodium. This is the error message that I encountered: Despite deleting all node mo ...

Encountering issues while establishing a connection to SQL Server through Node.js

I've developed a Node.js application to interact with SQL Server. Here's the code snippet: app.get('/SalesStatistics', function (req, res) { var Connection = require('tedious').Connection; // configuration for the databas ...

Learn the steps for converting data from xlsx or csv files into JSON format

I am currently working on developing an application that allows users to upload xlsx or csv files from the frontend and submit them to a backend built with nodejs and express for processing. However, when I receive the data in the backend, it appears in th ...

Developing tests for an asynchronous function

I recently encountered a bug in my AWS Lambda code written in NodeJS 6.10 that caused me two sleepless nights. I didn't conduct integration testing, relying solely on unit tests, which led to the oversight. After inserting return workerCallback(err);, ...

The Whatsapp webhook callback endpoint is experiencing a delay in being triggered

Currently, I am utilizing the Whatsapp cloud API and have successfully configured the webhook with a valid URL. While it is functioning correctly, there is an issue that arises when I receive a message from the business and immediately respond. The callbac ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Generating swagger documentation for TypeScript-based Express applications

I have successfully set up the swagger URL following a helpful guide on configuring Swagger using Express API with autogenerated OpenAPI documentation through Swagger. Currently, I am utilizing TypeScript which outputs .js files in the dist folder without ...

What is the best way to save the response data into an array outside of the current function in Node.js?

How can I efficiently store all the result data into an array called pImages? I am able to retrieve the results, but I believe using an async function would be more suitable. However, I am unsure of how to implement it. Any assistance would be greatly appr ...

An issue has occurred while running "gulp serve" as module.js is returning error code 471 and reporting that it cannot locate the module './build/release/encode

Setting up a vagrant box for my M.E.A.N project on Windows 10 and encountering an issue. Here's my environment: Node.js: v6.9.4 NPM: v4.2.0 Gulp: CLI v1.2.2 $ yo angular-fullstack $ sudo npm install $ gulp serve Upon running this command, I r ...

How can I use Selenium in Node.js to automatically add extensions to Firefox when it starts up?

I have attempted to use various examples from the documentation, but unfortunately none of them have been successful... Here is an example that adds an extension to Firefox and works almost perfectly: const webdriver = require('selenium-webdriver& ...

What is the best way to ensure my npm package on GitHub is up to

Is there a way to update npm packages on GitHub when the version dependencies are outdated? I do not own these packages, but my platform relies on them. When I update my Node.js version to the latest one, I encounter errors. Below are the commands I have ...

Utilize linear gradient effect in editing images and then convert them to base64 format using React

I have been working with the "canvas" library to edit an image via URL using linear-gradient, employing various methods. However, I am facing challenges in achieving the desired results so far. The methods I tried using canvas do not seem to work seamless ...

Challenges with setting up Vue.js

I've been attempting to install vue.js but have had no success, even though my npm is up to date. When I try running vue init webpack vueapp, I encounter the following error: No command 'vue' found, did you mean:Command 'vpe' fr ...

Adding to an existing array in MongoJS

I have been attempting to append data to an existing array in my mongoDB. The code snippet below is what I currently have, but unfortunately, it does not work as expected since all the existing data gets wiped out when I try to add new data: db.ca ...

Unexpected error encountered while trying to access npm bin parameter

I am currently in the process of developing a new npm package named loca-mapper. However, I have encountered an issue where the package does not run as expected when I include it in my scripts using map: loca-mapper and launch it with npm run map. Instead, ...

Developing a full stack web application using AngularJS, Node.js

I am interested in creating a web application that utilizes MySQL, Node.js, and AngularJS for CRUD operations. Can you provide guidance on how to start this project? Despite my efforts to develop the application, I have encountered numerous challenges and ...

Implementing a notification system similar to Stack Overflow in a Node.js and MongoDB application

Apologies if my inquiry seems vague, but let me explain my situation. I have a forum similar to StackOverflow, built on nodejs and mongodb. The forum includes posts and comments. I am in need of implementing a notification system that alerts users when a n ...