MongoDB on VPS with mongoose not inserting - node.js

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.

Related

MongoDB not authorized error on Ubuntu 16.04

I am installing a server on Digitalocean and have a MongoDB issue. I installed Mongo on the server and allowed remote access.
I created two users. One is super-user for me and the other is a regular user for the website users. I am able to connect to the mongo through Robomongo 3T (a mongo client) remotely for both users.
However, when I use the application from a browser, a simple login request gives an authentication error. Here is the error:
MongoError: not authorized on DATABASE_NAME to execute command { find: "users", filter: { email: "YYY", password: "XXX" }, limit: 1, singleBatch: true, batchSize: 1 }
Here is the realted server-side code:
Connecting the database at server.js:
MongoClient.connect(config.mongo_url, (err, client) => {
if(err) throw err
console.log('db connected')
app.locals.db = client
// start the server
app.listen(process.env.PORT || 3000, ()=>console.log('listening on port 3000!'))
});
Trying to connect to the local mongo on the server:
database.collection(config.mongo_col_user)
.findOne({
email: username,
password: hash
}, (err, user)=>{
if(err) return done(err)
if(!user) return done(null, false, {msg: 'not found'})
if(user.password)
return done(null, user)
})
I use pm2 on the server side and I use ecosystem.config.js which has the below code:
module.exports = {
apps : [
{
name: "NAME",
script: "SCRIPT_NAME",
watch: true,
env: {
"mongo_url": 'mongodb://USER_NAME:PASSWORD#localhost:27017?authMechanism=SCRAM-SHA-1&authSource=DATABASE_NAME',
"mongo_db_name": 'DATABASE_NAME',
"mongo_col_query": "COLLECTION_NAME",
}
}
]
}
Could you help with the problem please?
I have figured it out.
When I did make changes to pm2 environment file ecosystem.config.js, I did always restart pm2 with pm2 restart all. However, when you change the file, you should tell pm2 that you changed it by pm2 reload ecosystem.config.js --update-env.
Additionally, the correct syntax is no
mongodb://USER_NAME:PASSWORD#localhost:27017?authMechanism=SCRAM-SHA-1&authSource=DATABASE_NAME'
but
mongodb://USER_NAME:PASSWORD#localhost:27017/DATABASE_NAME'

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

Unable to connect to MongoDB using 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.

MongoDB auto_reconnect doesn't work

I'm using mongoskin as a wrapper to the native mongodb driver, auto_reconnect doesn't seem to work.
I'm creating the database:
var db = mongo.db(serverUrl, {
database: database,
auto_reconnect: true,
safe: true
});
I added a query on connection close to test it:
db.on('close', function(err) {
setTimeout(function() {
db.collection('users').findOne({short_id: '123'}, console.log);
}, 5000)
});
immediately after running the node process i'm killing and starting mongod, I'm getting '[Error: no open connections]' as the query result.
doesn't it suppose to auto_reconnect on connection lose ? or its trying to auto_reconnect immediately on connection close but mongod isn't up yet ?
can I reconnect manually or do I need to create a new server ?
Make sure you are using the latest node-mongodb-native (1.2.11) driver and it should work as you expect it to.

Resources