Getting started with node.js, Express and Mongoose

I started tinkering with some test data creation scripts using Node.js a while back, but it’s been on my todo list to dig deeper into some Node. I recently walked through this very good article, and got a REST based backend using Node.js, Express and a MongoDB up and running in less than an hour. Pretty good going for learning a new tech stack 🙂

After putting together the app from the steps in the article, I realized there was a few steps that could have been simplified. For example, instead of hand coding the package.json as in the article, you can let npm update it for you by passing the –save option. So, to create an initial package.json:

npm init

and walk through the prompts.

Next, instead of manually adding the dependencies for Express, Mongoose and body-parser, again, use npm to install and add them to the package.json file with –save:

npm install express --save

npm install mongoose --save

npm install body-parser --save

That saves some work – no need to edit the package.json file by hand when the tool maintains it for you. Without the –save option npm still downloads the dependency, but –save writes the details into your package.json as well.

Using Mongoose with Express certainly gets you up and running with basic CRUD using REST pretty quick and easy with minimal coding. I was surprised how little code it takes to get the basics implemented. I’ve shared my version of the completed app to GitHub for future reference here, and for quick reference below:

[code]

var express = require(‘express’);
var app = express(); //init Express
var bodyParser = require(‘body-parser’);
var mongoose = require(‘mongoose’);
var Contact = require(‘./app/models/Contact’);
mongoose.connect(‘mongodb://nodetest:yourpassword@localhost:27017/nodetest’);
//init bodyParser to extract properties from POST data
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

//init Express Router
var router = express.Router();

//default/test route
router.get(‘/’, function(req, res) {
res.json({ message: ‘App is running!’ });
});

router.route(‘/contacts/:contact_id’)
// retrieve contact: GET http://localhost:8080/api/bears/:bear_id)
.get(function(req, res) {
Contact.findById(req.params.contact_id, function(err, contact) {
if (err)
res.send(err);
res.json(contact);
});
})
// update contact: PUT http://localhost:8080/api/contacts/{id}
.put(function(req, res) {
Contact.findById(req.params.contact_id, function(err, contact) {
if (err) {
res.send(err);
}
else {
contact.firstName = req.body.firstname;
contact.lastName = req.body.lastname;
contact.save(function(err) {
if (err)
res.send(err);

res.json({ message: ‘Contact updated!’ });
})
}
});
})
//delete a contact
.delete(function(req, res) {
Contact.remove({
_id: req.params.contact_id
}, function(err, contact) {
if (err)
res.send(err);

res.json({ message: ‘Successfully deleted contact’ });
});
});

router.route(‘/contacts’)
// create contact: POST http://localhost:8080/api/contacts
.post(function(req, res) {
var contact = new Contact();
contact.firstName = req.body.firstname;
contact.lastName = req.body.lastname;

contact.save(function(err) {
if (err)
res.send(err);

res.json({ message: ‘Contact created!’ });
});
})
//GET all contacts: http://localhost:8080/api/contacts
.get(function(req, res) {
Contact.find(function(err, contacts) {
if (err)
res.send(err);

res.json(contacts);
});
});

//associate router to url path
app.use(‘/api’, router);

//start the Express server
app.listen(port);
console.log(‘Listening on port ‘ + port);
[/code]

Node.js and Mongoose: connection hanging on find()

Following this tutorial to build a simple REST api on Node.js with Express, attempting to retrieve all docs from my MongoDB gave these errors:

2016-05-19T20:10:47.311-0700 [initandlisten] connection accepted from 127.0.0.1:52053 #4 (2 connections now open)

2016-05-19T20:10:47.325-0700 [conn4]  authenticate db: nodetest { authenticate: 1, user: "", nonce: "xxx", key: "xxx" }

2016-05-19T20:10:47.336-0700 [conn4] Failed to authenticate @nodetest with mechanism MONGODB-CR: ProtocolError field missing/wrong type in received authenticate command

Some quick Googling turned up the same error in this post that just suggested authentication was failing because no user was passed. So created a new used with:

db.createUser({user : 'nodetest', pwd: 'passwordhere', roles: ['readWrite', 'nodetest']})

… and problem solved.

Microsoft teaming up with Red Hat for RHEL on Azure (and RH looking at node.js and Java integration options)

Red Hat recently announced a partnership with Microsoft where Microsoft is now offering Red Hat Enterprise Linux (RHEL) as an option on Azure. Although Microsoft has been offering Linux based IaaS offerings on Azure for a few years already, adding RHEL to the mix introduces an option with the backing of Red Hat enterprise support.

Red Hat are also apparently looking to increase integration options between Java and node.js for it’s clients, according to Rich Sharples, senior director for product management at Red Hat, recently speaking at a node.js conference in Portland.

node.js process.cwd() “no such file or directory” starting http-server

When starting the node.js http-server, I got this error:

[code]Error: ENOENT, no such file or directory
at Error (native)
at Function.startup.resolveArgv0 (node.js:720:23)
at startup (node.js:63:13)
at node.js:814:3[/code]

From the post here, it seems this error can occur if you attempt to start the server in a dir that’s already been deleted. In my case I had renamed a folder that contained the folder where I was attempting to start the server. cd’d up a couple and into the new/renamed folder, and problem solved.