Skip to content

Instantly share code, notes, and snippets.

@Pradeek
Created May 11, 2011 04:17

Revisions

  1. Pradeek revised this gist May 11, 2011. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion Model.js
    Original file line number Diff line number Diff line change
    @@ -16,7 +16,6 @@ var Article = mongoose.model('Article');

    ArticleProvider = {
    lastId : 0,
    articles : [],

    add : function(title, body, callback) {
    this.lastId++;
  2. Pradeek created this gist May 11, 2011.
    45 changes: 45 additions & 0 deletions Model.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    var mongoose = require('mongoose');
    mongoose.connect('YOUR_MONGODB_PATH');

    var Schema = mongoose.Schema;

    var ArticleSchema = new Schema({
    id : String,
    title : String,
    body : String,
    date : Date
    });

    mongoose.model('Article', ArticleSchema);

    var Article = mongoose.model('Article');

    ArticleProvider = {
    lastId : 0,
    articles : [],

    add : function(title, body, callback) {
    this.lastId++;

    var article = new Article();
    article.id = this.lastId;
    article.title = title;
    article.body = body;
    article.date = Date.now();

    article.save(function(error) {
    if(error) { throw error; }
    console.log("Article saved\n");
    callback();
    });
    },

    getArticle : function(articleId, callback) {
    Article.findOne( { id : articleId } , function(error, article) {
    if(error) { throw error; }
    callback(article);
    });
    }
    }

    exports.ArticleProvider = ArticleProvider;
    13 changes: 13 additions & 0 deletions node-mongoose-example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    var http = require('http'),
    ArticleProvider = require('./Model').ArticleProvider;

    http.createServer(function(request, response) {
    ArticleProvider.add('Hello Node', 'NodeJS + MongoDB via Mongoose', function() {
    ArticleProvider.getArticle(1, function(article) {
    response.writeHead(200, { 'Content-Type' : 'text/plain' });
    response.write(article.id + " : " + article.title + "\n");
    response.write(article.body + "\n");
    response.end();
    });
    });
    }).listen(8000);