Issue with node.js and mongoskin error handling - node.js

I am learning and trying simple example using node.js and mongoskin. here is my function below
Problem following function is, if the mongodb server is disconnected then also I get the "err=null" hence not able catch connection error. If I restart node.js server (while mongoDB server is still disconnected) I get error as
"[Error: failed to connect to [server-aa070:27017]]"
// Process messages from client
app.post('/send', function(req, res){
var message = {
id: i++,
nickname: req.param('nickname', 'Anonymous'),
text: req.param('text', ''),
created_at: new Date()
};
conn.chat_log.insert(message, function(err) {
if(err!==null){
console.log(err);
}
else {
console.log(message);
console.log(err);
}
});
res.json({status: 'ok'});
});

I'm new to node.js and mongodb, but why are you using if(err!==null) rather than if(err)? If I'm understanding correctly, wouldn't this solve your problem?

Don't know about mongoskin, but for the node-mongo-native driver (the driver that mongoskin is built on), the author said:
Note that there's no reason to pass a callback to the insert or update
commands unless you use the safe:true option. If you don't specify
safe:true, then your callback will be called immediately.

Related

Problems Deploying a Node.js app on Heroku Using MongoLab

I'm attempting to deploy a very simple app to Heroku. The code for the application can be found on Ray Wenderlich's site, here: http://www.raywenderlich.com/61078/write-simple-node-jsmongodb-web-service-ios-app I keep getting the same error whenever I try to have Heroku compile the code...
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
var mongoPort = 41140;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort)); //B
mongoClient.open(function(err, mongoClient) { //C
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1); //D
}
var db = mongoClient.db("heroku_app23491233"); // E
collectionDriver = new CollectionDriver(db); //F
});
When I type heroku logs, the error I get comes from if (!mongoClient) above...
app[web.1]: Error! Exiting... Must start MongoDB first
I'm sure the problem lies somewhere in my attempt to connect to the MongoLab database. I've copied the URI from MongoLab and I've created a user with the proper credentials.
I can connect to localhost just fine with very similar code, so I'm not sure what is going wrong in this example.
Thank you.
Based on the docs, my best guess is that it's because the Server constructor expects the first argument to contain only the host name (in the case of your MongoLab, ds041140.mongolab.com). However, I think you can pass your connection string into MongoClient.connect:
// Make sure to replace username and password with the proper values.
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
MongoClient.connect(mongoHost, function(err, db) {
if (err) return console.log(err);
db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
db.close();
if (err) return console.log(err);
console.log('Okay', result);
});
});
Documentation Page For MongoClient
Hopefully that helps!

MongoDB with Node.js PUT problems

I am working through the Developing Backbone.js Applications and I am trying to set up example2 which involves installing node.us with npm and Mongodb.
All seems to be installed properly, I can do some poking around mongodb with the mongo console, node.js is running fine, got my example server running and (seemingly) no errors on connecting to the mongodb:
//Connect to database
mongoose.connect( 'mongodb://localhost/library_database', function(err) { if (err)
console.log(err); } );
No errors... but on an attempt to post:
jQuery.post( '/api/books', {
'title': 'JavaScript the good parts',
'author': 'Douglas Crockford',
'releaseDate': new Date( 2008, 4, 1 ).getTime()
}, function(data, textStatus, jqXHR) {
console.log( 'Post response:' );
console.dir( data );
console.log( textStatus );
console.dir( jqXHR );
});
I'm getting a server 500 errors... no indication from the console or DB that anything was even attempted.
The get works fine, though there's nothing in the database, it comes back empty, but I can't get the post to work.
Can anyone suggest a process for debugging this? Is it possible my DB is configured read only?

Couchbase get / getMulti fails on timeout in node.js

I'm new with Couchbase and trying to use the couchbase module 1.2.1, the connection to the DB seems to work fine, but the get and getMulti operations are failing and the error I'm getting is "Operation timed out".
I tried to increase the timeout, but it didn't help.
var db = new couchbase.Connection({ host:'localhost:8091', bucket:'beer-sample'},
function(err){
if (err){
throw err; // not getting here
}
});
db.get("id", function(err, result) {
if (!err && result){ // getting error
req.id = result;
}
});
What can be the problem?
You should try to reinstall Couchbase Server and try again using a host of 127.0.0.1:8091.
What version of Couchbase Server, and what platform/architecture you are using would also be helpful to know.

Mongodb find() method freezes over Nodejs

I'm starting webapps development with Node, so I'm quite new with this technology.
I've done several examples and managed to make it run.
However, now I'm trying to use Mongodb but I'm not able to make it run properly. It seems that the connection is working but when I call the find() method and I go to localhost:3000/near (which is the url that makes the findAll docs), the browser spends about a half a minute loading and finishes returning nothing (ERR_EMPTY_RESPONSE).
This is my code:
app.js
app.get('/near', function(req, res){
server.findAll( function(error,docs){
res.render('near', {
title: 'Cerca tuyo!',
places:docs
});
})
});
And this my Server.js
//constructor
AppServer = function(host, port) {
this.db= new Db('node-mongo-places', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
//Devuelve la colección de "places"
AppServer.prototype.getCollection= function(callback) {
this.db.collection('places', function(error, places_collection) {
if( error ) callback(error);
else callback(null, places_collection);
});
};
//Devuelve todos los contenidos de la DB places
AppServer.prototype.findAll = function(callback) {
this.getCollection(function(error, places_collection) {
if( error ) callback(error)
else {
places_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
I have debugged the code writing console.log() and it seems that it does not reach to the callback function from places_collection.find().toArray(function(error, results) {
Any idea why the server does not return anything?
!!! EDIT:
I found some piece of code to test if the connection to mongodb is alright and it says that it's not: [Error: failed to connect to [localhost:27017]]
So the problem is in the connection. Should I run mongodb first? I thought that the app.js itself would did that for me!
Got the answer for this question:
As said, I thought that npm install mongodb would install the whole thing. However, it does not, so I managed to fix it by executing sudo apt-get install mongodb.
Once installed, the app itself runs mongodb.
I added this to my mongodb open() method so as I could see what was happening:
this.db.open(function(error,db){
if(error) {
console.log(error);
} else {
console.log("connected to mongod with no problems...");
}
});

Why isn't the MongoClient in my Node.js script finishing?

I have a one-shot Node script that makes some changes to a MongoDB database on MongoLab. However, once it finishes, it never exits the event loop (I always have to ctrl+C it), no matter how much db.close() and db.logout() calling I do.
What's strange is, if I start a local running instance of mongod and connect to that, the script finishes fine, but the remote connection just never ends.
Here is a short version of my script that still has the issue (taking the URL to the server on the command line). What's going on?
var mongodb = require("mongodb");
function onSuccess(cb){
return function(err) {
if (err) {
console.error(err)
} else {
cb.apply(this,Array.prototype.slice.call(arguments,1))
}
}
}
console.log("Connecting to "+process.argv[2]+' ...');
mongodb.MongoClient.connect(process.argv[2],onSuccess(function(db){
console.log("Connected.");
db.logout(onSuccess(function(logoutResult){
db.close(onSuccess(function(closeResult){
console.log("All finished. Can has prompt return nao?")
}));
}));
}));
Just tried the code with driver version 1.2.7/1.2.8 and the newest 1.2.9 against mongolab and it works correctly. So more likely its a weird combination of driver/os/node version that's causing this. I suggest upgrade your node and driver to the latest version and try again.
I suspect it has to do with the way you have defined your closures but I cannot quite put my finger on it.
For what is worth, below is the approach that I use and this does close the connection as expected:
MongoClient.connect(dbUrl, function(err, db) {
if(err) return callback(err);
var collection = db.collection(dbCollection);
collection.find().toArray(function(err, items){
db.close()
if(err) return callback(err);
callback(null, items);
});
});
You can find a full example here: https://github.com/hectorcorrea/mongoDbSample

Resources