Mongo db connection to node js without ODM error handling - node.js

I am comfortable with crud operations in mongo db and just want to perform crud operations in my app . I don't have good reason to use ODM .Here's my working code with nodeScheduler as my DB
let {MongoClient} = require('mongodb')
let connect =() =>{
const uri ="mongodb://localhost:27017";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("nodeScheduler").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
}
My Question is then :
If I give non-existent db then also I am getting in console Connected successfully to server. How do I validate existent db's and existent collections with Mongo Driver

Related

how node js connect with mongodb using tcp?

How the tcp connection is established and closed during the database call?
The below code is to get lists of databases in mongodb using mongoclient in nodejs
async function main(){
const uri = "mongodb+srv://<username>:<password>#<your-cluster-url>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
await client.connect();
await listDatabases(client);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
1.Does the "await client.connect()" establish a tcp connection with mongoDb?
2.Does the "await client.close()"close a tcp connection with mongoDb?
3.How does the mongodb and nodejs communicate using tcp ?
node-mongodb-native's .connect() and .close() manage a Topology of Servers that have Monitored Connections communicating via a MessageStream

create new tedious connection every time for a new API call?

I am working on creating Express JS as my API server, using tedious to connect to my SQL Server DB.
Currently, in every request logic, I'll create a new tedious Connection object, connect to the DB, execute the query, then close the connection.
import { Connection } from 'tedious';
export class Controller {
all(_: Request, res: Response): void {
const connection = new Connection(getConfig()); // create a new connection everytime
connection.on('connect', (err) => {
if (err) {
console.log('Connection Failed');
throw err;
}
getProducts(connection, _, res); // in there at the end, will call connection.close()
});
connection.connect();
}
import { Request, Response } from 'express';
import { Connection, Request as SqlReq } from 'tedious';
export default function getProducts(connection: Connection, _: Request, res: Response) {
const query = `SELECT * FROM Production.Product FOR JSON PATH;`;
let resultJson = ''; // prepare this result in return from SQL query
const sqlReq = new SqlReq(query, (err, _) => {
if (err) {
throw err;
}
// when request finished
connection.close();
res.json(JSON.parse(resultJson));
});
Is it a good or bad practice to create the connect, connect and close every time for a new API call? If there is a better way to handle the connection, may I have any reference or example?
just make sure that the connection is created only once by using this function. It will create the connection only on first call and return the previously created connection on subsequent calls.
var connection = null;
const getConnection = async () => {
if (connection) return connection;
connection = new Connection(getConfig());
return tmp;
};
Then you should leave the connection open by not calling close.
Better use connection pooling in mysql. During app startup, you can create a pool of threads used for db connecting purpose. It will be very fast, if you retrieve from the pool and establish the connection.
After your query execution/ manipulation, ensure to release the connection. So it will go to connection pool and available for further requests.
Ref : How do I create a MySQL connection pool while working with NodeJS and Express?
Ref : Release connection
node.js + mysql connection pooling

Can not connect to azure cosmos db from azure function App using Node.js

I am trying to send the incoming data from the IoT in the cosmos DB.
I am receiving data in the function app but sadly I am not able to connect the cosmos DB using the connection string provided( in cosmos DB quickstart and connection string blade.
Below is my node.js application:
module.exports = function (context, IoTHubMessage) {
try {
var dbName = "temp-db";
var collectionName = "messages";
context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessage}`);
context.log(`datatype of message: ${typeof IoTHubMessage}`);
var json_message = JSON.stringify(IoTHubMessage);
context.log(`json message: ${json_message}`);
var mongoClient = require("mongodb").MongoClient;
context.log('MongoClient created');
const pass = "Q********************XTB988aNw4CecjmZsSqTpCeXkjlzCrmljzjq58T9AqeuVvSJrUPBpc4rBSSD1CQ=="
const encodedpass = encodeURIComponent(pass)
const connectionString= `mongodb://iot-db:${pass}#iot-db.documents.azure.com:10255/?ssl=true`
context.log(`connection string:\n ${connectionString}`)
mongoClient.connect(connectionString, function (err,client){
context.log('check0...');
if(err){
context.log(`Error occurred while connecting to DB ${err}`)
} else{
context.log('MongoClient connected to DB');
}
context.log('check1...');
var collection = client.db(dbName).collection(collectionName);
context.log('MongoClient collection retreived');
collection.insertOne(IoTHubMessage, {w: 1});
//collection.insertOne({"testKey": 13.56}, {w: 1});
client.close();
context.log(`Saved message: ${IoTHubMessage}`);
context.done();
});
context.log('check2...');
} catch (e){
context.log(`Error ${e}`);
}
context.log('Done called');
context.done();
};
Here are the issues that I am facing:
The above app does not give any error, but while running the call back function is not getting executed.( i know this because the prints are not happening inside the callback function.)
I tried to pass the non-URI encoded password. then it enters the callback function but complains that the password contains illegal characters.
on passing the encoded password it does not enter the callback function.
How do I check which node driver I am currently using?
How do I check if my 10255 port is open or not?
I am attaching a screenshot of the node.js app

Kontainer-di with Mongo Native

I'm trying to get the MongoDB Native Driver to work with Kontainer-di. I want to add the connected client (returned from the connect method) to the container so that I can inject it into the controllers/services directly.
There is an option to use a start function which returns a promise which I thought would work with the mongo native connect function. The database is connected inside the then. My issue is that I'm not sure how I can access the connected database client to add the session to the container.
My code so far looks like:
var mongoClient = require('mongodb').MongoClient;
var promise = require('bluebird');
var mongoFactory = function(config) {
function start() {
return mongoClient.connect("mongodb://127.0.0.1:27017/test", {promiseLibrary: promise})
.then(function(database) {
console.log('mongo connection initialised');
})
.catch(function(err) {
console.error('Error: ', err);
});
}
function stop() {
db.close();
}
return {
start: start,
stop: stop
}
}
module.exports = mongoFactory;
In case somebody else has the same issue as me. I ended up going with the mongojs library instead which doesn't use promises for the connection so the active connection could easily be added to the container.
I still wanted to use promises rather than callbacks for the queries so I used bluebird and it's promisifyAll method.

How to reconnect mongoose to another remote server?

I am totally new to node.js and mongoose, how to reconnect mongoose to another remote server ?
At the beginning of the file I have
var mongoose = require('mongoose')
and connected to localhost,
later in code I have
var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };
// Connect to Database
mongoose.createConnection(uristring, mongoOptions, function (err, res) {
if (err) {
console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
} else {
console.log ('Successfully connected to: remote' + uristring);
}
});
and I always get Successfully connected to: remote but when I bellow that print look for document by id I get always from local database(I have schema imported like require Person = mongoose.model('Person');).
How to reconnect to remote if I already have connection to local.
There are two ways of initializate a connection in mongoose:
Using the default connection "object"
Creating a connection from the dust
Here you are creating a connection, but using a model from another. Models are tied to databases (normal databases, replica sets or clusters) so you're not accesing to the correct host.
You must use the default connection (using mongoose.connect instead of mongoose.createConnection) or create a model in that new connection you are using. In your example:
var uristring ='mongodb://remote_server/db';
var mongoOptions = { db: { safe: true } };
// Connect to Database
var newConnection = mongoose.createConnection(uristring, mongoOptions);
newConnection.model(/*whatever*/);
mongoose.model wires to mongoose.connection. That is not the new connection you have created.

Resources