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();
}
})
}
})
}