Unable to query MongoDB using a localhost URL and MongoJS - node.js

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

Related

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

How to connect mongodb Replicaset in 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?

NodeJS Mongoose handle database connection failed exception

I'm building a restful web service api using NodeJS.It uses Mongoose as ODM and using MongoDB for backend.
Below i will explain my scenario
I started nodejs server
After that i shutdown the MongoDB database.
Then call the GET api call,it doest catch any errors and api call get hang.
database config in main.js file
var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb';
mongoose.Promise = global.Promise;
var options = { server: {socketOptions: { keepAlive: 300000, connectTimeoutMS: 10000 } } } ;
mongoose.connect(uri,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'connection refused !!!!!'));
db.once('open', console.log.bind(console,'connection success !!!!!'));
this is my basic GET call
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var rootRes = require('../model/rootresources.js');
router.get('/', function(req, res, next) {
rootRes.find({},function (err, rootResource) {
if (err){
console.log('Error occurd !!!') }
res.json(rootResource);
});
});
Even database connection failed, the code does not goes to error block. So didn't capture the database refuse when database connection is failed in the API call.
I want to capture that error and send internal server error (code:500) to client. I tried to find the solution but still could not find it
Any solutions or do i made a mistake ?
Thank you
Amila
Did you put the two parts of code in the same file(ie. main.js) or two different files.
put them in the same file, and run node main.js do throw exceptions.
// main.js
var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb';
mongoose.Promise = global.Promise;
var options = { server: {socketOptions: { keepAlive: 300000,
connectTimeoutMS: 10000 } } } ;
mongoose.connect(uri,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'connection refused !!!!!'));
db.once('open', console.log.bind(console,'connection success !!!!!'));
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var rootRes = require('../model/rootresources.js');
router.get('/', function(req, res, next) {
rootRes.find({},function (err, rootResource) {
if (err){
console.log('Error occurd !!!') }
res.json(rootResource);
});
});
exceptions are:
connection refused !!!!! { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
etc...
So, I think maybe you put codes about express in a file like index.js and codes about mongoose connection in another file. And just run node index.js in command line. While running codes in index.js will not include codes in other files, codes in main.js will not be executed. As the result, there is no error info.
Updates
Two ways of I know two ways of doing this:
1.In main.js create function which creates connection to database and returns a instance of db so that you can call it function in you main code.
// main.js like this
var mongoose = require('mongoose');
function createConnection(url) {
mongoose.connect(url,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'refused !!!!!'));
db.once('open', console.log.bind(console,'success !!!!!'));
return db;
}
// export function
module.exports = createConnection;
// in your index.js
var createConnection = require('./main.js');
var db = createConnection(url);
// other codes here
2.Using require or vm to compile and run javascipt code. You can find vm api detail here
//main.js
var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb';
mongoose.Promise = global.Promise;
var options = { server: {socketOptions: { keepAlive: 300000,
connectTimeoutMS: 10000 } } } ;
mongoose.connect(uri,options);
var db = mongoose.connection;
db.on('error',console.log.bind(console,'connection refused !!!!!'));
db.once('open', console.log.bind(console,'connection success !!!!!'));
// index.js
// require will load file and execute automaticly
var scriptSrc = require('./main');
// other codes here
You can think of the second way as using eval('var mongoose = require('mongoose');
var uri = 'mongodb://localhost/mydb'; etc...)
mongoose connection do not happen unless you hit a request. so its best you handle it in your first request middleware. see code insight bellow.
module.exports = function () {
return function (req, res, next) {
mongoose.connect(URL, MONGO_OPTIONS);
mongoose.connection
.once('open', () => { })
.on('error', (error) => {
res.status(401).json({});
});
...
Then pass the middleware above to your router: let me know if you need more explanation
router.get('/', myMiddleware(){})

How can I connect to mongodb using express without mongoose?

I am using the express framework and would like to connect to a mongodb without using mongoose, but with the native nodejs Mongodb driver. How can I do this without creating a new connection every time?
To handle get or post requests I currently open a new connection to the db for every request and close it on completion of the request. Is there a better way to do this? Thanks in advance.
Following the example from my comment, modifying it so that the app handles errors rather than failing to start the server.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var dbURL = "mongodb://localhost:27017/integration_test";
var db;
// Initialize connection once
MongoClient.connect(dbURL, function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here
// because most apps *should* fail to start if they have no DB.
// If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
app.get("/", function(req, res, next) {
var collection = "replicaset_mongo_client_collection";
db.collection(collection).find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});
app.use(function(err, req, res){
// handle error here. For example, logging and
// returning a friendly error page
});
// Starting the app here will work, but some users
// will get errors if the db connection process is slow.
app.listen(3000);
console.log("Listening on port 3000");
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/dbname';
module.exports = function(callback) {
mongodb.MongoClient.connect(uri, callback);
};
Ad this snippet in a file say connect.js and then require this file(connect.js) in your file where you are declaring your functions for http requests.

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(...);

Resources