Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda