Unable to connect to MongoDB using node.js - node.js

I installed MongoDB in my machine and I'm able to start mongod and connect to the db using the mongo command. I even imported some data in the mycol collection of the mydb db:
$ sudo start mongodb
mongodb start/running, process 31008
$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use mydb
switched to db mydb
> db.mycol.count();
5730
> ^C
bye
But now if I want to access the db via node.js it doesn't work anymore, I get a TypeError.
I try this code (UPDATED):
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mydb', function(err, db) {
if(err) throw err;
console.log("connected!");
});
This is based on the npm module mongodb, I also tried mongoose and mongojs, each time with the same result. As soon as I want to connect to the database, I get a TypeError.
$ node mngclient.js
Failed to load c++ bson extension, using pure JS version
events.js:172
throw TypeError('type must be a string');
^
TypeError: type must be a string
at TypeError (<anonymous>)
at EventEmitter.once (events.js:172:11)
at Server.Base._registerHandler (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/base.js:387:23)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/server.js:410:12)
at EventEmitter.emit (events.js:91:17)
at null.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:111:15)
at EventEmitter.emit (events.js:97:17)
at Socket.<anonymous> (/home/odi/dev/mydb/node_modules/mongodb/lib/mongodb/connection/connection.js:297:10)
at Socket.EventEmitter.emit (events.js:116:20)
at Object.afterConnect [as oncomplete] (net.js:848:10)
UPDATE:
The version of the mongodb npm package is 1.3.23
npm outdated shows no output, so I guess my packages are up-to-date
Using mongoose with the following very simple code brings up the exact same error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
UPDATE II:
I still couldn't resolve this issue on my machine
I setup the whole project in a virtual machine using vagrant. It works like a charm.

You should read the document , your trying to start a server(I'm not sure why?) here is an example on connecting to the mongo database you already have running :
MongoClient.connect('mongodb://localhost:21017/myDb', function(err, db) {
"use strict";
if(err) throw err;
...//your code
});

Step 1: npm install mongodb
Step 2: create a file, name it suppose : app.js
Paste the following content into the file:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'myDB';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
Step 3 : node app.js
Step 4: run mongod and mongo, check updated db list using show dbs
Database will be created and a collection named 'documents' will be added over there.

Related

"Failed to lookup instance on (localdb)" when the full instance name is "(localdb)\\MSSQLLocalDB"

I'm trying to do a simple select query to my database with node.js via the mssql package, but the it seems that the server property of my connection string doesn't take the full string and stop at (localdb) instead of the full server name which is (localdb)\MSSQLLocalDB
Code :
let sql = require('mssql');
sql.connect({
server:'(localdb)\\MSSQLLocalDB',
database:'xxx',
options:{
trustedConnection:true
}
},function(err){
if(err) console.log(err);
var request = new sql.Request();
request.query('simple query',function(err,recordset){
if(err) console.log(err);
res.send(recordset);
})
})
Error :
ConnectionError: Failed to lookup instance on (localdb) - getaddrinfo ENOTFOUND (localdb)
Was there a change on how mssql in node checks the instance link or am I doing something wrong?
Thanks a lot ! :)

MongoDb how to get all the objects in the document from client side

I am trying to save the whole MongoDB object in the schema but I can only get the undefined value only
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url,function(err,db){
if(err){
console.log("no connect")
}
var dbo = db.db("mydb");
var query = {name:"Company Inc"};
dbo.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
Actually it is throwing error
W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: errno:111 Connection refused
I am connecting to the DB and I want to get the all the data from the MongoDB document
Thanks in advance!

db.collection is not a function

I am trying to simply insert an entry in a MongoDB collection using Nodejs. Here is my code:
code:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
db.collection('Todos').insertOne({
text: 'Something to do',
completed: false
}, (err, result) => {
if (err) {
return console.log('Unable to insert todo', err);
}
console.log(JSON.stringify(result.ops, undefined, 2));
});
db.close();
});
When I run the code, it showing the following error:
error:
TypeError: db.collection is not a function
Uninstalling existing mongodb package and reinstalling using the following commands resolved the issues
npm uninstall mongodb --save
npm install mongodb#2.2.33 --save
Version MongoDB >= 3 - That database variable is actually the parent object of the object you are trying to access. If u using mongo 3+:
const myDb = db.db('YourDatabase')
myDb.collection('YourDatabase).insertOne ....
you can rewrite your code as follow
MongoClient.connect(url,(err,db) =>{
const database= db.db('TodoApp')
database.collection('Todos').insertOne({})
}
The reason for this error is the version of the NodeJs Driver. TypeError: db.collection is not a function. If the version is > 3.0.1 then you have to change the db to client. For more info check this page, it helped me!
[db.collection is not a function when using MongoClient v3.0
Hope that helps!

Problems connecting to MongoDB server from MongoLab

I'm trying to connect to mongodb created by MongoLab, but it always seems to fail.
var mongoose = require('mongoose');
mongoose.connect('mongodb://<dbuser>:<dbpassword>#ds123854.mongolab.com:12345/the_db');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function (err) {
console.log('Could not connect to mongo server!');
console.log(err);
});
// check if mongoose connected; 0 = no; 1 = yes; 2 = connecting; 4 = disconnecting
console.log("mongoose connection: " + mongoose.connection.readyState);
I get the log:
mongoose connection: 2
Could not connect to mongo server!
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
I tried to check the password, so I did the following in my console:
> mongo ds123854.mongolab.com:12345/the_db -u <dbuser> -p <dbpassword>
MongoDB shell version: 3.0.7
connecting to: ds123854.mongolab.com:12345/the_db
rs-ds123854:PRIMARY> db.mynewcollection.insert({ "foo": "bar"})
WriteResult({ "nInserted" : 1 })
rs-ds123854:PRIMARY> db.mynewcollection.find()
{ "_id" : ObjectId("563c1913504f0ab5cb96d74c"), "foo" : "bar" }
The username and password seem right and I can see that the insert command did put something into the database.
I am hosting my server in localhost, so I believe that's the problem. What sort of things am I missing in my configuration?
Solution: Ensure that your version of Mongoose is up to date.
In my case, I was using version 3.6.13, but the current version is 4.2.4
If you specified your mongoose version, just update your package.json file and use command line npm update

MongoDB on VPS with mongoose not inserting

I created a simple demo using mongoose, which works perfectly on localhost:
mongoose.connect('mongodb://localhost/mindmap', function(err, next) {
if(err) return next(err);
console.log('database connected');
});
It fetches data with a simple find:
/* GET mindmaps. */
router.get('/', function(req, res, next) {
Mindmap.find(function (err, mindmaps) {
if (err) return next(err);
res.json(mindmaps);
});
});
And adds data through socket connection
// handle adding new mindmaps
socket.on('mindmap.add', function (data) {
Mindmap.create(data, function (err, mindmap) {
if (err) throw err;
mindmaps.push(mindmap);
io.sockets.emit('mindmap.add', mindmap);
});
});
Now all of this is working fine locally.
Today I installed npm, bower, the app itself and MongoDB on my CentOS 6.5 VPS. I started the mongo service and on the server changed app.js to connect to the correct ip/port:
mongoose.connect('mongodb://127.0.0.1:27017/mindmap', function(err, next) {
When I start the app with node bin/www the connect does not throw any errors and simply states that the database is connected. The /mindmap gives an empty array (which is logical at this point). Adding a new mindmap through the socket connection even emits a proper mindmap object and the html will display it. There's no errors, but also nothing is saved and on a refresh it starts empty again. Also in the mongo shell there's nothing in the collection.. and if I add something manually I can't see it in /mindmap.
Full client-side code is on http://mindmap.solidwebcode.com:3000/mindmap
For reference this is the model:
var mongoose = require('mongoose');
var SubjectSchema = new mongoose.Schema({
title: String,
x: Number,
y: Number,
w: Number,
h: Number,
parent: mongoose.Schema.Types.ObjectId
});
var MindmapSchema = new mongoose.Schema({
name: String,
theme: String,
subjects: [SubjectSchema],
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Mindmap', MindmapSchema);
I installed mongodb using:
sudo yum --enablerepo=epel install mongodb mongodb-server
sudo service mongod start
Also starting mongo works as expected, although there's some warnings:
Server has startup warnings:
2015-05-04T13:42:08.955+0200 [initandlisten]
2015-05-04T13:42:08.955+0200 [initandlisten] ** WARNING: You are running in OpenVZ which can cause issues on versions of RHEL older than RHEL6.
2015-05-04T13:42:08.955+0200 [initandlisten]
I have never before installed mongo on a VPS and used it. Am I missing something trivial?
The problem is not MongoDB is not working, but rather that the socket connection was started to localhost:3000, which is not the same as the external server.. so while nothing happends on the remote server, the local server was accepting the socket connection and adding new records in it's own database.
Solution was simple: change the socket connect to a remote address.

Resources