express

"hello world" steps to start coding with MondoDB, NodeJS and Mongoose

by
published on
This steps will use Mongoose Object data model. Just so that i don't forget the simple syntax i will keep it posted here. Installation:  (Skip steps which are already done) Mongodb -
$ brew update
$ brew install mongodb
Then navigate to your project folder and install express, node, bla bla bla stuffs.. Guessing we did that already.Next.. Add mongoose to the project
$ npm install mongoose
Now coding. Add Mongoose dependency:
var mongoose = require('mongoose');
Add MongoDB connection
var db = mongoose.connect('mongodb://localhost/users123');

Define a schema. This is like table structure but in a different format.
//New Schema Object
var Schema = mongoose.Schema;

//Schema Definition
var UserSchema = new Schema({
name: String
})

//Register schema to Mongoose
mongoose.model('User', UserSchema);

The above code is good enough to display if you have any data in your database, but you will need the below code to display it. To display use this:
/* GET home page. */
router.get('/', function(req, res, next) {
mongoose.model('User').find(function(err, users) {
res.send(users);
});
});

To add data, once the schema is defined add the following:
//User model using User schema available in Mongoose.
var UserModel = mongoose.model('User');

//Create a new User Object
var user = new UserModel();

//Add the info to the attributes
user.name = "Kaushik1";

//Save it
user.save(function(){

//Do stuffs after save if you want to.
console.log("Saved");
});
Add good reference tutorial is this: http://cdnjs.com/libraries/backbone.js/tutorials/nodejs-restify-mongodb-mongoose