a simple CRUD web using nodejs (expressjs f/w, hbs templating) and mongodb

Simple CRUD web using Nodejs and MongoDB

a simple CRUD web using nodejs (expressjs f/w, hbs templating) and mongodb
a simple CRUD web using nodejs (expressjs f/w, hbs templating) and mongodb

In this article, i just want to share my one day experiment with node.js and mongodb. I build a simple web that does CRUD in node.js and save the records to MongoDB. I stupidly built this although this post says that build CRUD in node.js is a bad use case :p

Skip the talks, lets go to the points. I built this on Windows. I need (of course) node.js and mongodb, go to their websites, download and install them to your computer. Once you got them installed then you are ready to code.

Next step is get a HTML template for user interface, if you are LAZY like me just use Bootstrap, from twitter. I need their awesome HTML CSS tables and forms, icons right away. Download and use one of their examples, i am using the fluid layout. User interface? Done.

This is the hardest part (for me), code in node.js. Step one, to make this easier i have to install expressjs. In your app directory type this…

npm install -g express

express “D:/monode-crud” (this is depend on you app directory)

Line one will install expressjs as node modules on your app, and line two will create a directories that expressjs needed. Go to expressjs.com for complete guide.

I don’t like the jade that expressjs used as their default template engine. Instead of using jade, i am installing another node modules called hbs. What is hbs? Hbs is a view engine for express.js. Here is hbs website https://github.com/donpark/hbs. Hbs is basically a handler for Handlebars.js, a Mustache.js-like template engine. Both of them are logic less templates.

npm install hbs

After you are finished installing hbs, then modify your node.js app configurations.
[code=”javascript”]
var hbs = require(‘hbs’);
….
….

app.engine(‘html’, require(‘hbs’).__express);
app.set(‘views’, __dirname + ‘/views/html’);
app.set(‘view engine’, ‘html’);
[/code]

And then copy all the assets (image, javascript, css files) from bootstrap to “public” directory. Put your .html template under “views” directory.

In order to connect to Mongodb to store the records, i am using node-mongodb-native. There are many other libraries to do this, but IMHO, this is the easiest way to connect node.js and mongodb. Install this via npm as usual.

npm install mongodb

Okay. All done. 🙂

Check out the complete node.js app and codes at my github page. Here is the repo.

Please drop your comments or questions through this blog or follow me @hadiariawan at twitter. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *