0

Tengo un problema a la hora de conectar la base de datos que he creado con Mongo DB Atlas con Apollo server. No se si el problema reside al haber creado el modelo con mongoose, y utilizar posteriormente MongoClient en el archivo dbConnection.js, en vez de utilizar mongoose. Estoy algo perdido. Os pongo el código para ver si me pudieráis orientar a resolver el problema. Gracias de antemano.

en app.js

const express = require('express');
    const {ApolloServer} = require('apollo-server-express');
    const typeDefs = require('../src/graphql/shema');
    const resolvers = require('../src/resolvers/resolvers');
    const  connectToDatabase  = require('../src/mongodb/dbConnection');
    //import middleware cors to enable  on the express server
     const cors = require('cors');
    
    console.log('connectiontoDB',connectToDatabase)
    //import library dotenv
    require('dotenv').config({path:'.env.local'});
    
    
    const startServer = async()=>{
    
        const app= express();
    
        //This code block tells to express server to accept cross-origin requests (CORS) only from the specified URL client
        //cors config.:
        
            //url where the client(frontend) is running
            const clientUrl= process.env.CLIENT_URL;
            // console.log('clientUrl',clientUrl)
    
        app.use(cors({
            origin: clientUrl,
            credentials: true
        }));
    
        //connection to MongoDB using Mongoose
    
        // await connectToDatabase();
    
        const client = await connectToDatabase();
        if(!client){
            console.error('Failed to connect to MongoDB');
            process.exit(1);
        }
        console.log('Connected to MongoDB');
          
    
    
        //config Apollo Server
        // instance apollo server
        const server = new ApolloServer({
            typeDefs,
            resolvers,
            context: () => ({db: client.db('flash-card-app')}),
           
    
        // apollo server init
        await server.start();
    
     
        //Apollo Server middleware is applied to the /graphql path.
        // disables apollo-specific CORS, as i already handle it with express
        server.applyMiddleware({app, path: '/graphql', cors: false});
       // server.applyMiddleware({app})
    

    
        const PORT = process.env.PORT || 4000;
        console.log(PORT)
        const DATABASE_NAME = process.env.DATABASE_NAME;
        const COLLECTION_NAME = process.env.COLLECTION_NAME;
        console.log('db_name', DATABASE_NAME);
        console.log('collection_name', COLLECTION_NAME);
    
        //Endpoint to obtain data from Mongo DB
        app.get('/', async(req, res)=>{
            try {
                // const data = await Flashcard.find({});
                const database = client.db(DATABASE_NAME);
                console.log('database', database)
                const collection = database.collection(COLLECTION_NAME);
                console.log('collection', collection)
                const data = await collection.find({}).toArray();
                console.log('data', data)
                res.json(data);
            }catch(error){
                console.log(error, error.message);
                res.status(500).json({ error: 'Error connecting to MongoDB'});
            }
        });
       
    
         
    
        app.listen(PORT, ()=>{
            console.log(`Server listening on PORT: http://localhost:${PORT}/${server.graphqlPath}`)
    })
    
    }
    
    startServer().catch(error=>{
        console.error('Error starting server:', error);
    });

En schema.js

const { gql } = require('apollo-server-express');

const typeDefs= gql`

    type Flashcard {
        _id: ID!
        question: String!
        answer: String!
        isAnswered: Boolean
    }

    type Query {
        getFlashcard(_id: ID!): Flashcard
        allFlashcards: [Flashcard]
    }

    input FlashcardCreateInput {
        question: String!
        answer: String
    }

    input FlashcardUpdateInput {
        question: String
        answer: String
        isAnswered: Boolean
    }

    type Mutation {
        createFlashcard(input: FlashcardCreateInput) : Flashcard
        updateFlashcard(_id: ID!, input: FlashcardUpdateInput) : Flashcard
        deleteFlashcard(_id: ID!) : Flashcard
    }

`;

module.exports = typeDefs;

en models/flashcard.js

    const mongoose = require('mongoose');
    
    const  { Schema } = mongoose;
    
    const FlashcardSchema= new Schema({
        question: {
            type: String,
            required: true,
        },
        answer: {
            type: String,
            required: true,
        },
        isAnswered: {
            type: Boolean,
            default: false,
        },
    });
    
    module.exports = mongoose.model('flash-card-app', FlashcardSchema);

En dbConnection.js

const { MongoClient } = require('mongodb');

require('dotenv').config({path:'.env.local'});

const uri = process.env.MONGODB_URI;
console.log('uri',typeof uri);


let client;

const connectToDatabase=async()=>{
 if(client && client.topology.isConnected()){
  return client;
 }
  

try {
  //instance of MongoClient
  client = new MongoClient(uri);
  

  await client.connect();
 // console.log('client',client)
   console.log('Connected successfully to MongoDB Atlas using MongoClient');
  return client;
  // return mongoose.connection;
} catch (error){
  console.error('MongoDB connection error', error);
  throw error;
}

};
console.log('connectToDatabase', connectToDatabase)

module.exports = connectToDatabase;

en resolvers.js

const resolvers = {
   // we provide a function that takes the same parameters (as the corresponding query/mutation)
   // and uses them  database manipulation functions.
    Query: {
        async getFlashcard(_, {_id}, {db}){
            try {
                const flashcard =await db.collection('flash-cards').findOne({_id});
                return flashcard;
               
              } catch (error) {
                console.error('Error fetching flashcard by ID:', error);
                throw new Error('Error fetching flashcard');
              }
        },
        async allFlashcards(_,__,{db}){
            try {
                const flashcards= await db.collection('flash-cards').find().toArray();
                return flashcards;
               
              } catch (error) {
                console.error('Error fetching all flashcards:', error);
                throw new Error('Error fetching flashcards');
              }
            },
            
    },
    Mutation: {
        async createFlashcard(_, {input}, {db}){
            try {
              const newFlashcard= await db.collection('flash-cards').insertOne(input);
              return newFlashcard.ops[0];
               
              } catch (error) {
                console.error('Error creating flashcard:', error);
                throw new Error('Error creating flashcard');
              }
        },
        async updateFlashcard(_, {_id, input}, {db}){
            try {
              const updatedFlashcard= await db.collection('flash-cards').findOneAndUpdate(
                {_id: _id},
                {$set: input},
                {returnOriginal:false}
              );
              return updatedFlashcard.value;
              } catch (error) {
                console.error('Error updating flashcard:', error);
                throw new Error('Error updating flashcard');
              }
        },
        async deleteFlashcard(_, {_id}, {db}){
            try {
              const deletedFlashcard = await db.collection('flash-cards').findOneAndDelete({_id});
              return deletedFlashcard.value;
              } catch (error) {
                console.error('Error deleting flashcard:', error);
                throw new Error('Error deleting flashcard');
              }
            },
        },
};

module.exports = resolvers;

Buenas a todos! Tengo un problema a la hora de conectar la base de datos que he creado con Mongo DB Atlas con Apollo server. No se si el problema reside al haber creado el modelo con mongoose, y utilizar posteriormente MongoClient en el archivo dbConnection.js, en vez de utilizar mongoose. Estoy algo perdido. Os pongo el código para ver si me pudieráis orientar a resolver el problema. Gracias de antemano.

Mensaje de error:

Diagnosing localhost:3100/graphql ⚠️ POST response missing 'access-control-allow-origin' header. If using cookie-based authentication, the following headers are required from your endpoint: access-control-allow-origin: studio.apollographql.com access-control-allow-credentials: true Otherwise, a wildcard value would work: access-control-allow-origin: * (📫 Interested in previewing a local tunnel to bypass CORS requirements? Please let us know at docs.google.com/forms/d/e/… )

5
  • Hay algún mensaje de error en la consola? Hay que compartir esos detalles
    – g.4
    Commented el 24 may. a las 16:28
  • @g.4 Diagnosing localhost:3100/graphql ⚠️ POST response missing 'access-control-allow-origin' header. If using cookie-based authentication, the following headers are required from your endpoint: access-control-allow-origin: studio.apollographql.com access-control-allow-credentials: true Otherwise, a wildcard value would work: access-control-allow-origin: * (📫 Interested in previewing a local tunnel to bypass CORS requirements? Please let us know at docs.google.com/forms/d/e/… ) Commented el 28 may. a las 15:04
  • ok logras ver este mensaje en node? console.log('Connected successfully to MongoDB Atlas using MongoClient');, o ¿el error aparece en la consola de node o cuando intentas usar apollo studio desde ` localhost:3100/graphql`?
    – g.4
    Commented el 28 may. a las 19:44
  • @g.4 El error aparece en la consola cuando intento usar apollo studio Commented el 29 may. a las 19:07
  • Revisa esta configuración: apollographql.com/docs/apollo-server/security/cors/…
    – g.4
    Commented el 30 may. a las 6:07

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.