MongoError: Topology is closed, please connect
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
:
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 reuseconst dbURL = 'mongodb://localhost:27017';const dbName = 'projectdb';// Made each function async/await// Swapped the datasource's findOneById() for the collection itself & standard Mongo functionsclass 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/awaitconst resolvers = { Query: { item: async (_, { id }, { dataSources }) => { return await dataSources.items.getItem(id); }, }}// Move the ApolloServer constructor to its own function that takes the dbconst 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 MongoClientMongoClient.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...