Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
Couldn't connect to mongodb database to make graphql queries

My graphql queries work with the local DB file but while trying to connect to MongoDB it doesn't work as expected.

mongo.js

require("dotenv").config();
const mongoose = require("mongoose");
const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
    throw new Error(
        "Please define the MONGODB_URI environment variable inside .env.local"
    );
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections from growing exponentially
 * during API Route usage.
 */
let cached = global.mongoose;

if (!cached) {
    cached = global.mongoose = { conn: null, promise: null };
}

async function dbConnect() {
    if (cached.conn) {
        return cached.conn;
    }

    if (!cached.promise) {
        const opts = {
            bufferCommands: false,
        };

        cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
            return mongoose;
        });
    }
    cached.conn = await cached.promise;
    return cached.conn;
}

module.exports = dbConnect;

MONGODB_URI=mongodb+srv://xxxx:xxxx@cluster0.yxbw7.mongodb.net/?retryWrites=true&w=majority

graphql query to get all the products:

exports.typeDefs = gql`
    type Query {
        products: [Product!]!
    }

    type Product {
        id: ID!
        name: String!
        description: String!
        price: Float!
        image: String!
    }

`;

Resolvers:

const { Product } = require("../models/Product");

exports.Query = {
    products: async (parent, args, context) => {
        let products = await Product.find({}).exec();
        return products;
    },
};

The DB has data in it but still making the query,

query{
  products {
    description
    id
    name
    price
    image
  }
}

It returns an empty product array,

{
  "data": {
    "products": []
  }
}

Something seems wrong with MongoDB to connect with graphql, the queries work with the local DB file which has a dummy object product data.

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!