Isaac Limón
Isaac Limón

Reputation: 2058

mongodb insertOne inside a loop

I want to insert different collections inside a loop. I already wrote this and it works once.

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

let insertflowers = async (collectionname,query) => {
    try {
        await client.connect();
        const database = client.db('flowers');
        const collection = database.collection(collectionname);
        return await collection.insertOne(query);
    } finally {
        await client.close();
    }
}

insertflowers('alocasias',{name:'...'}).catch(console.dir);

What I want to do is put it inside a loop like this.

arrayofflowers.forEach( val => {
    let flowerType = ...
    insertflowers(flowerType,{name:'...'}).catch(console.dir);
});

But I get the following error MongoError: Topology is closed, please connect Thank you for reading

Upvotes: 0

Views: 570

Answers (1)

In short remove await client.close();


Check https://docs.mongodb.com/drivers/node/usage-examples/insertMany/ to insert bulk records at once.


You're in race condition so when insertflowers process is running in parallel connection is closed and opening.

So when you try to insert data connection is closed by another call to insertflowers.

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

let connection;

const connect = async () => {
  if (!connection) { // return connection if already connected
    connection = await client.connect();
  }
  return connection;
});

let insertflowers = async (collectionname,query) => {
    try {
        const conn = await connect();
        const database = conn.db('flowers');
        const collection = database.collection(collectionname);
        return await collection.insertOne(query);
    } finally {
        console.log('insertflowers completed');
        // await client.close(); remove this
    }
}

Another option - Not a good idea though

Make insertflowers is run the sync.

Upvotes: 1

Related Questions