Automattic / monk

The wise MongoDB API
MIT License
1.85k stars 182 forks source link

MongoError: Topology is closed, please connect #290

Closed GodBleak closed 4 years ago

GodBleak commented 4 years ago

Hi, I am receiving this error when inserting a documentMongoError: Topology is closed, please connect

This is my code

const monk = require('monk')
const url = 'mongodb+srv://user:pass@cluster0-hcldh.mongodb.net/sample_airbnb';
const db = monk(url);
const lar = db.get('listingsAndReviews')

lar.insert({name: "Lovely Loft", summary: "A charming loft in Paris", bedrooms: 1, bathrooms: 1})

// db.then(() => {
//   console.log('Connected correctly to server') //this works
// }).catch((error) =>{
//   console.log(error);
// })

What have I done wrong?

ganeshtedi commented 4 years ago

did u got solved @GodBleak ...

GodBleak commented 4 years ago

@ganeshtedi I moved on from monk when I closed this. I used MongoJS and got the same issue. I figured out that in MongoDB Atlas I couldn't use the URI string for version "3.0 or later" the URI string for version "2.2.12 or later"

Looks like this: mongodb://godBleak:@cluster0-shard-00-00-hcldh.mongodb.net:27017,cluster0-shard-00-01-hcldh.mongodb.net:27017,cluster0-shard-00-02-hcldh.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority

shaqshaw commented 4 years ago

I am still stuck on this issue as well.

how i defined my mongo connection:" mongoose.connect(keys.mongoURI, { useUnifiedTopology: true, useNewUrlParser: true, }) .then(() => { console.log("DB Connected!"); }) .catch(err => { console.log(DB Connection Error: ${err.message}); }); const User = mongoose.model('user'); "

how i defined my query:" const existingUser = await User.findOne({name: name}} "

error: " MongoError: Topology is closed, please connect "

GodBleak commented 4 years ago

@shaqshaw1 what does your keys.mongoURI look like?

tejas2706 commented 4 years ago

Try connecting using MongoClient, in this manner :-

const MongoClient = require('mongodb').MongoClient;

const client = new MongoClient(, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect( err =>{ if(err) return console.log(err) const db = client.db(""); })

axeleli commented 3 years ago
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://root:<password>@cluster0.vksdv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect(err => {
    const collection = client.db("chatapp").collection("chat");
    // perform actions on the collection object
    try {
        collection.insertOne( { item: "card", qty: 15 } );
    } catch {
        throw(err)
    }
    console.log('connected')
  });

Topology is closed, please connect

checked db names etc

Yossitrx commented 3 years ago

Getting the same thing when trying to preform:

app.post("/bitChange", async (req, res) => {
  const mongoClient = await client.connect();
  const dbo = mongoClient.db("leads_db");
  try {
    await dbo
      .collection("bit_rate")
      .updateOne(
        { name: "bit" },
        { $set: { change: req.body.change } },
        function (error, record) {
          if (error) throw error;
          res.json("done");
        }
      );
  } catch (e) {
    console.log("e");
    throw Error(e);
  } finally {
    client.close();
  }
vatsa287 commented 3 years ago

mongodb-client does not allow for multiple connections to be on. So empty the 'finally' block by removing client.close. It worked for me but the warnings are still persisting.

gh-andre commented 3 years ago

MongoClient.close returns a promise and needs to be waited on to work without errors or warnings. A new instance of MongoClient needs to be allocated either via static MongoClient.connect or via instance connect, like this.

async function insertOne(doc: any) : Promise<void>
{
  let client: MongoClient | undefined;

  try {
    client = await MongoClient.connect(uri, {
                          useNewUrlParser: true,
                          useUnifiedTopology: true
                        });

    // OR
    client = new MongoClient(uri, {
                          useNewUrlParser: true,
                          useUnifiedTopology: true
                        });
    await client = client.connect();

    const col = client.db("mydb").collection("mycol");

    await col.insertOne(doc);
  }
  finally {
    if(client)
      await client.close();
  }
}
iamraufu commented 3 years ago

Sometimes the incorrect password or database name or collections name occurs this error. However, you can add allow access from anywhere to resolve this issue.

yashwanth2407 commented 3 years ago

Even I got the same error as @GodBleak , then I opened Mongodb atlas and in "Network Access", I changed the IP address as "0.0.0.0/0 (includes your current IP address) ". Then my problem got resolved.

rav3n11 commented 2 years ago

@yashwanth2407 is there any way to do this without using aMongodb atlas? A command?

gh-andre commented 2 years ago

@rav3n11 This opens your database instance to anyone on the Internet to probe for vulnerabilities. Not a good idea to follow this advice in any form.