0

I am learning to use the mongodb native driver along with nodeJS and ExpressJS. I am new to NodeJS so please bear with me.

The UI CLIENT sends data to the REST API endpoint and the POST call inserts the data (document) into MongoDB collection.

When I am going through the examples at MongoDB native driver documentation, I notice that collection.insertOne, collection.save are always performed as a callback to the mongo_client.connect. I don't understand this because I want to connect to mongo_client once and continue to update the collection and bring down the connection (mongo_client.close) when the express server is brought down. I understand that callbacks are safe.

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

// Use connect method to connect to the server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  insertDocuments(db, function() {
    client.close();
  });
});

Why do I have to connect for every CRUD operation? save the state of the connection to the db/collection and cannot reuse?

My existing code:

const express = require('express')
const app = express()
const server_port = 64726
const MongoClient = require('mongodb').MongoClient;

const insert_user = (id, email)=> {

mongo_client.connect(err => {
console.log("mongo connect function called....")
assert.equal(null, err)
console.log ("connected successfully to DB ")
const mongo_user_collection = mongo_client.db(mongo_db_name).collection("users");
mongo_user_collection.save ({'_id':id,'email':email,'lastlogin': new Date() })
// perform actions on the collection object
// mongo_client.close();
});
}


app.post ('/api/login/verify', (req, res) => {
    insert_user(req.body.id,req.body.email);
})

app.listen(server_port, ()=>{
console.log('Server started...')
})

In my code, I see for every post call I need to connect and then insert the document. How to avoid this behavior so I can Connect once, reuse connection and insert docs for every POST call?

James Z
  • 12,209
  • 10
  • 24
  • 44
javapedia.net
  • 2,531
  • 4
  • 25
  • 50
  • Does this answer your question? [How to properly reuse connection to Mongodb across NodeJs application and modules](https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module) – Stephen S Dec 14 '19 at 15:45
  • thanks for the suggestion, will check and confirm. – javapedia.net Dec 14 '19 at 19:45
  • thanks the link helped. However my scenario is very simple, so included the change in my index.js itself – javapedia.net Dec 14 '19 at 22:19

1 Answers1

0

This worked for me. Thanks all for the suggestions.

const mongo_client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true  });
let mongo_user_collection;

mongo_client.connect(err => {
    console.log("mongo connect function called....")
    assert.equal(null, err)
    console.log ("connected successfully to DB ")
 mongo_user_collection = mongo_client.db(mongo_db_name).collection("users");

});


const insert_user = (id, email)=> {
mongo_user_collection.save ({'_id':id,'email':email,'lastlogin': new Date() })
}


app.post ('/api/login/verify', (req, res) => {
    insert_user(req.body.id,req.body.email);
})

app.listen(server_port, ()=>{
console.log('Server started...')
})
javapedia.net
  • 2,531
  • 4
  • 25
  • 50