1

I want to store unique values into a collection. I am using Node.js and MongoDb. However, If I try to Insert within Find promise then it says "MongoError: server instance pool was destroyed"

And I cannot access the data within collection outside Find promise. Kindly help me, I am really not understanding how to work around this async pattern.

function addToDBAs( data ){
mongo_client.connect(url, (err, db)=>{
    if(err)
        console.log(err)
    else{
        var dbo = db.db('uniqueSet')
        dbo.createCollection('entities',(err, res)=>{
           if(err)
               console.log(err)
           else{
               console.log("collections created")
               let collection = dbo.collection('entities')
               let dataObjs = []
               collection.find().toArray((err, items) => {

                    data = new Set( data, items )
                    data = Array.from(data)

                    data.map(entity => dataObjs.push({name: entity}))

                    dbo.collection('entities').insertMany(dataObjs)

                console.log(items)
              })
              db.close();
           }
       }) 
    }
})
}
Rusty
  • 4,138
  • 3
  • 37
  • 45
  • 2
    Though the problem here is indeed calling `close()` before the `insertMany()` operation is complete, the main causal problem is that establishing a connection within a functional unit and then closing is just bad practice. See [How to properly reuse connection to Mongodb across NodeJs application and modules](https://stackoverflow.com/q/24621940/2313887) in order to learn that you in fact connect **once** and then share the connection reference around the rest of the application as long as it runs. – Neil Lunn Apr 20 '19 at 03:30

1 Answers1

1

You are calling db.close() before insertMany has finished. You need to wait for the completion insertMany using async / await or Promise.then

It should be something like this (with async / await pattern)

dbo.createCollection('entities', async (err, res) => {
if (err) console.log(err)
 else {
  console.log('collections created')
  let collection = dbo.collection('entities')
  let dataObjs = []
  const items = await collection.find().toArray()
  data = new Set(data, items)
  data = Array.from(data)
  data.map(entity => dataObjs.push({ name: entity }))
  await dbo.collection('entities').insertMany(dataObjs)
  db.close()
 }
})
anton62k
  • 371
  • 1
  • 6