Mongoose.js Jump Start PRO

Mongoose.js JavaScript library provides us with an object oriented interface for using the MongoDB database in our node.js web applications. You can easily install this JavaScript library using the npm utility. The npm utility is available once you install node.js on your desktop. If you are not familiar with node.js and the npm utility you can do your first steps using the node.js free course I have developed. You can find it at http://abelski.lifemichael.com.

Once the mongoose module is available you can easily use it in your code. The following code sample shows how simple it is to use it.

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

var db = mongoose.connection;

db.on('error', function() {console.log("error")});

db.once('open', function () {
  console.log("connected!");
  var productSchema = mongoose.Schema({id:Number, name: String});
  productSchema.methods.printDetails = function() {
  	var str = "id=" + this.id + " name="+this.name;
  	console.log(str);
  };
  var Product = mongoose.model('storeproducts',productSchema);

  var carpeta = new Product({id:123123,name:'carpetax'});
  var tabola = new Product({id:432343,name:'Tabolala'});
  carpeta.save(function(error,prod) {
  	if(error) {
  		console.log(error);
  	}
  	else {
  		console.log("carpeta was saved to mongodb");
  		carpeta.printDetails();
  	}
  });
  tabola.save(function(error,prod) {
  	if(error) {
  		console.log(error);
  	}
  	else {
  		console.log("tabola was saved to mongodb");
  		tabola.printDetails();
  	}
  }); 

  Product.find(function(error,products) {
  	if(error) {
  		console.log(error);
  	}
  	else {
  		console.log(products);
  	}
  });
});

The following video clip overviews this code sample, shows its execution and explains each and every part of it.

You can find more free resources for learning how to use this library in my free online courses web site at http://abelski.lifemichael.com.

Share:

banner for the css playlist in hebrew life michael courses for programmers

The First Steps in CSS

Learn CSS using our our videos (in Hebrew) on the CSS (he) playlist on youtube. Do it now. Do it for free.

Good Trainers Collaborate with Others

It is always essential to keep an open mind and learn from others. This applies to everyone, including teachers and especially software development trainers. Software

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences