1

I am getting the error "MongoError: Cannot use a session that has ended" and after looking through a few other stackoverflow similar questions, majority of have been solved by using async/await due to the doing multiple things at once. I tried this my self but with no luck, In may case I am doing a single action and still getting this error.

Any suggestions or tips?

const mongodb = require('mongodb');
const mongoclient = mongodb.MongoClient;
const client = new mongoclient(uri, { useNewUrlParser: true, useUnifiedTopology: true  });

client.connect(err => {
  if(err) return console.log(err);

  const collection = client.db(databasename).collection(nameofcollection);
  collection.insertMany(details);
  client.close();
});
JaySnel
  • 163
  • 2
  • 12

2 Answers2

2

The close action is faster than the insertMany action, because it does not wait until the end of the asynchronous function. Try this:

const DB = client.db(databasename);

const myAsyncFunction = async() => {
  const collection = await DB.collection(nameofcollection); // do this INSIDE async function

  await collection.insertMany(details); // similarly inside async
};

client.close();

Or you can try smth like this:

client.connect(err => {
  if(err) return console.log(err);

  client.db(databasename).collection(nameofcollection)
      .then(collection => collection.insertMany(details))
      .then(() => client.close());
});
Yuriy Vorobyov
  • 755
  • 4
  • 8
  • Thanks for this. First option worked like a charm and something ill be keeping in mind for the future. – JaySnel Dec 13 '20 at 17:10
0

Maybe it helpful to use this function:

    var Mongoclient =require('mongodb').MongoClient;

function write_item( db_name,  collection_name,  data){

    var url = "mongodb+srv://ignacio:gaona@cluster0.bjhns.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
;    /*put your url from mongo atlas here*/

Mongoclient.connect(url,function(err, db){
  

    var collection_internal =  db.db(db_name).collection(collection_name);
    console.log("MongoUtils--Connected");
    collection_internal.insertOne(data).then(()=> {
        db.close();
        console.log("MongoUtils--writed");
        console.log("MongoUtils--DisConnected");}) ;
    
  
  
});}




module.exports = write_item;
NachFenix
  • 11
  • 1
  • 4