falconzy's Blog

My Learning Path

Getting Started Mongoose

installation

$ npm install mongoose

Connection

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tasks');
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
// conding here;
//Once connection opens,callback will be called here.
});

Disconnect

mongoose.disconnect();

REGISTERING A SCHEMA

With Mongoose, everything is derived from a Schema.

var Schema = mongoose.Schema;
var Tasks = new Schema({
        project: String,
        description: String
});

Next step is compiling our schema into a Model.

mongoose.model('Task', Tasks);

ADDING A TASK

var Task = mongoose.model('Task');
var task = new Task();
task.project = 'Bikeshed';
task.description = 'Paint the bikeshed red.';
task.save(function(err) {
    if (err) throw err;
    console.log('Task saved.');
});

SEARCHING FOR A DOCUMENT

var Task = mongoose.model('Task');
Task.find({'project': 'Bikeshed'}).each(function(err, task) {
    if (task != null) {
        console.log('ID:' + task._id);
        console.log(task.description);
        } 
});

UPDATING A DOCUMENT

var Task = mongoose.model('Task');
Task.update(
    {_id: '4e65b793d0cf5ca508000001'}, \\Update using internal ID
    {description: 'Paint the bikeshed green.'},
    {multi: false}, \\Only update one document
    function(err, rows_updated) {
        if (err) throw err;
        console.log('Updated.');
    }
);

REMOVING A DOCUMENT

var Task = mongoose.model('Task');
    Task.findById('4e65b3dce1592f7d08000001', function(err, task) {
    task.remove();
});

Extra

add methods to our documents:
methods must be added to the schema before compiling it with mongoose.model()

Tasks.methods.list = function () {
var greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name"
    console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema)

Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance:

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. The first argument to the callback will be an error if any occured.

fluffy.save(function (err, fluffy) {
    if (err) // TODO handle the error
    fluffy.speak();
});

We can access all of the documents through model.

Kitten.find(function (err, kittens) {
    if (err) // TODO handle err
    console.log(kittens)
})

filter by name, Mongoose supports MongoDBs rich querying syntax.

Kitten.find({ name: /^Fluff/ }, callback)

This performs a search for all documents with a name property that begins with “Fluff” and returns the results to the callback.