MongoError: Topology is closed, please connect

前端 未结 2 1589
小蘑菇
小蘑菇 2021-01-18 16:07

I\'m a front-end dev trying to expand my horizons on a new Next project, learning Node, Mongo, and the server side of GraphQL for the first time. Apollo strikes me as the ea

相关标签:
2条回答
  • 2021-01-18 16:48

    Actually there is one more thing that may be causing this as I also had the same exact error "Topology Closed, please connect".

    The thing is if you have a dynamic IP address then in MongoDB atlas you should try allowing all IP addresses.

    Add the IP address: 0.0.0.0/0 All my problems were solved after whitelisting this IP address which allows all.

    Image of dynamic IP 0.0.0.0/0:

    0 讨论(0)
  • 2021-01-18 17:03

    Thanks to GitHub's "Used By" dropdown on the apollo-datasource-mongodb I was able to cheat off a few other repositories, and here's what I ended up with (with changes marked in comments):

    const { MongoClient } = require('mongodb');
    const assert = require('assert');
    const { ApolloServer, gql } = require('apollo-server');
    const { MongoDataSource } = require('apollo-datasource-mongodb');
    
    
    // Isolated these for prominence and reuse
    const dbURL = 'mongodb://localhost:27017';
    const dbName = 'projectdb';
    
    // Made each function async/await
    // Swapped the datasource's findOneById() for the collection itself & standard Mongo functions
    class Items extends MongoDataSource {
      async getItem(id) {
        return await this.collection.findOne({id: id});
      }
    }
    
    const typeDefs = gql`
      type Item {
        id: Int!
        title: String!
      }
      type Query {
        item(id: Int!): Item
      }
    `;
    
    // Made each query async/await
    const resolvers = {
      Query: {
        item: async (_, { id }, { dataSources }) => {
          return await dataSources.items.getItem(id);
        },
      }
    }
    
    // Move the ApolloServer constructor to its own function that takes the db
    const init = (db) = {
      return new ApolloServer({
        typeDefs,
        resolvers,
        dataSources: () => ({
          items: new Items(db.collection('items')),
        }),
      });
    }
    
    // Use .connect() instead of new MongoClient
    // Pass the new db to the init function defined above once it's been defined
    // Call server.listen() from within MongoClient
    MongoClient.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
      assert.equal(null, err);
      const db = client.db(dbName);
      console.log(`Mongo database ${ dbName } at ${ dbURL }`);
    
      const server = init(db);
    
      server.listen().then(({ url }) => {
        console.log(`Server ready at ${ url }`);
      });
    });
    

    With these changes, the Apollo Playground at localhost:4000 works great! Now to solve the 400 error I'm getting in my client app when I query...

    0 讨论(0)
提交回复
热议问题