-
-
Save luiselizondo/1794252 to your computer and use it in GitHub Desktop.
NodeJS + MongoDB via Mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment