Accessing MongoDB Documents Properties in ExpressJS App - node.js

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

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

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')
})

MongoJS returns no results while MongoClient does

I am trying to connect to MongoDB with Node.js. MongoClient works fine, but Mongojs doesn't:
var MongoClient = require('mongodb').MongoClient;
var mongojs = require('mongojs');
var url = '...';
MongoClient.connect(url, function(err, client) {
var cursor = client.db("events").collection('events').find();
cursor.each(function(err, event) {
console.log("OK MONGODB");
});
});
mongojs(url, ['events']).events.find(function(err, events) {
events.forEach(function(event) {
console.log("OK MONGOJS");
});
});
"OK MONGODB" is logged several times; "OK MONGOJS" is not.
What's wrong, please?
In your case, the url used in MongoClient should be different with mognojs.
Suppose the url is 'mongodb://localhost/', it is OK for MongoClient. However, the url used in mongojs should be added with dbname as following
var db = mongojs('mongodb://localhost/mydb', ['mycollection']);
So it should be as below
mongojs(url+'events', ['events']).events.find(...);

TypeError: Object #<MongoClient> has no method 'db' solution vs Documentation

While going through a mongodb tutorial, I ran into an issue with this configuration:
var MongoClient = require('mongodb').MongoClient;
var mongoClient = new MongoClient(new server('localhost', '27017', {'native_parser': true}))
var db = mongoClient.db('test');
TypeError: Object # has no method 'db'
Eventually, I was able to solve it using mongodb server
var server = require('mongodb').Server,
Db = require('mongodb').Db;
var db =new Db('test', new server('localhost', '27017', {'native_parser': true}));
db.open(function(err, res){
app.listen(8080);
console.dir('app started on 8080');
});
However, the documentation says "Server should not be used, use the MongoClient.connect."
Based on this, I'd like to know when is the appropriate time to use the server?
Here is an example on how to use it in regards to the deprecation present in 2.0 and your setup and usage of callbacks instead of promises:
var mongoDB = require('mongodb');
var theDB = null;
mongoDB
.MongoClient
.connect('mongodb://localhost:27017/test', null, function(err, db) {
if (err) {
console.error(err);
} else {
theDB = db;
app.listen(8080);
console.dir('app started on 8080');
}
});

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