How to connect mongodb Replicaset in node.js - node.js

I have tried this:
const mongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:4000,localhost:4001/bookstore?replicaSet=myapp';
mongoClient.connect(url,(err,db)=>{
if(err){
return;
}
console.log('connected to the database');
})
But how to export the database object(db)? The db object can be get only in the callback. Could you please give me some advice?

Related

Not Able to Connect to Password-protected MongoDB Server/DB

After successfully testing my Node app against a local mongoDB db, I am now trying to connect to our server db - which, unlike my local mongoDB, is user and password protected.
I am running into issues while trying the connection to the server. Specifically, I am getting this error:
MongoError: MongoClient must be connected before calling
MongoClient.prototype.db
The creds I'm trying look something like this:
{
"MONGO_URL": "mongodb://myuser:mypassword#someurl.com:27017?authSource=admin",
"MONGO_DATABASE": "bta",
"MONGO_COLLECTION": "jobs"
}
And here is my connection code:
const config = require('./configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
async function getJobDetails() {
client.connect(async function () {
try {
const db = await client.db(dbName);
// do stuff
});
} catch (error) {
console.log(error);
}
});
}
What am I missing here?
I figured out what the issue was and was able to get it to connect. The issue was that the site is secure, so I had to add ssl=true to the url connection string:
const url = 'mongodb://user:password#someurl.com:27017/bta?ssl=true&authSource=admin';
try:
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(url, { useNewUrlParser: true }, function(client_err, client) {
if (client != null) {
var client_db = client.db(dbName);
}
client.close();
});
As MongoDB.
https://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
And please Try double checking DB on the server if it has the right config.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL with password example
const url = 'mongodb://user:password#address:27017?readPreference=primary&authSource=admin';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// 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);
client.close();
});
This works for both valid localhost/server url

TypeError: 'connect' only accepts a callback

when I try node index.js my error comes with TypeError: 'connect' only accepts a callback, then I'm confused about how to solve this problem.
The error goes to mongo_client.js:165:11
I did a tutorial about how to connect to mongodb with Nodejs but, I found a problem that ppl never had since now
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient();
const url = 'mongodb://localhost:27107/testedmtdev';
MongoClient.connect(url, function(err, client){
if(err){
console.log('Unable to connect to the Mongodb server. Error : ', err);
} else {
app.listen(3000, ()=>{
console.log('Connected to mongodb, webservice running on port 3000');
})
}
});
I expect the output of 'Connected to mongodb, webservice running on port 3000'
It's because you're actually calling MongoClient with no parameters.
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient(); // <-- your calling the method here
Make a change to just use a reference
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient; // <-- do *not* call method
https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect

Accessing MongoDB Documents Properties in ExpressJS App

I have the following code and I am trying to fetch documents from the MongoDb database and display the first name property of each document. For some reason I get the following error:
TypeError: Cannot read property 'firstName' of undefined
Here is my app.js implementation:
const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var db = {}
var url = 'mongodb://localhost:27017/bank';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
this.db = db;
console.log("Connected correctly to server.");
db.close();
});
app.get('/customers',function(req,res){
console.log("customers")
this.db.open()
var documents = this.db.collection("customers").find()
documents[0].firstName // how to access the first name property
this.db.close()
res.send("fetching customers")
})
What can i see in code is this.
you have a global scope variable .
var db = {};
and then you are doing
MongoClient.connect(url, function(err, db) {
do staff
when you do
db.close(); the client is close;
})
and when you are opening the this.db.open(); next time the connection is close for mongoclient.
either don't do db.close() or
create mongoclient when you do query

Unable to query MongoDB using a localhost URL and MongoJS

This is the tasks.js code I'm trying to run:
/*jslint node:true*/
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('mongodb://localhost:27017/tasks', ['tasks']);
router.get('/tasks', function (req, res, next) {
'use strict';
db.tasks.find(function(err, tasks) {
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
The code is meant to query and display all the contents of the json file.
When I replace the db localhost URL with this mLab URL:
var db = mongojs('mongodb://username:password#ds161008.mlab.com:61008/mytasklist_muhab', ['tasks']);
It works perfectly.
I assume there is a problem with the string. I looked up the connectionString standards in MongoDB docs and I couldn't locate the problem.
I haven't assigned any username or password to the local database.
Mongod is running fine and I am able to run commands on the same database using the Mongo shell without any problem.
According to mongojs documentation you may no need to use mongodb://localhost:27017 as part of your connectionString for local db can try by only dbName
like:
var db = mongojs('tasks', ['tasks'])
or
var db = mongojs('tasks')
var mycollection = db.collection('tasks')
and checked your connection established or not by using error or connect event
var db = mongojs('tasks', ['tasks'])
db.on('error', function (err) {
console.log('database error', err)
})
db.on('connect', function () {
console.log('database connected')
})

How to include and use connection.js file in node.js application of mongodb

connection.js
/**
* lets require/import the mongodb native drivers.
*/
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database';
/**
* Use connect method to connect to the Server
*/
MongoClient.connect(url,function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else {
console.log('Connection established to', url);
var collection = db.collection('users');
db.close();
}
});
I prefer to just connect mongodb in the app.js, and only keep the passwords or url in an external file. But if you're going to do it your way.
Assuming your instance of mongoDB is running, and you're using the native driver for node, your connect.js should look like this:
// Require
var MongoClient = require('mongodb').MongoClient, assert = require('assert');
// Location
var url = 'mongodb://localhost:27017/myproject';
// Connect
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
Then your app.js will require your connect.js. It should look something like this
var db = require('...path to connect.js');
Don't forget to include mongoDB drivers in all of your models, then export your models. You then import your models into each controller you use them in.

Resources