Skip to content

Instantly share code, notes, and snippets.

@Pradeek
Created May 11, 2011 04:17
Show Gist options
  • Select an option

  • Save Pradeek/965914 to your computer and use it in GitHub Desktop.

Select an option

Save Pradeek/965914 to your computer and use it in GitHub Desktop.
NodeJS + MongoDB via Mongoose
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;
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);

ghost commented Mar 21, 2016

Copy link
Copy Markdown

Your code no optimize!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment