MongooseJS

Mongodb object modeling for node.js

Mongoose provides schema-based solution to modeling application data and includes built-in type casting, validation, query building, business logic hooks and more.

Be sure you have MongoDB and Node.js installed.

$ npm install mongoose

// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
// with Mongoose, everything is derived from a Schema
var kittySchema = mongoose.Schema({
    name: String
})
// adding methods to the schema
kittySchema.methods.speak = function () {
  var greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name"
  console.log(greeting);
}
// compiling our schema into a Model
var Kitten = mongoose.model('Kitten', kittySchema);

var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak() // "Meow name is fluffy"
// each document can be saved to the database by calling its save method. 
fluffy.save(function (err, fluffy) {
  if (err) // TODO handle the error
  fluffy.speak();
});

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>