Skip to content

Instantly share code, notes, and snippets.

@yumu19
Created November 4, 2014 10:06
Show Gist options
  • Save yumu19/744c27c930aa1a13b536 to your computer and use it in GitHub Desktop.
Save yumu19/744c27c930aa1a13b536 to your computer and use it in GitHub Desktop.
node.js file which saves body of HTTP POST to MongoDB
var http = require('http');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dataSchema = new Schema({ data: Schema.Types.Mixed});
var Data = mongoose.model('data', dataSchema);
mongoose.connect('mongodb://localhost/test');
http.createServer(function (req, res) {
if(req.method=='POST') {
var body = '';
req.on('data', function (dat) {
body +=dat;
});
req.on('end',function(){
var doc = new Data({ data: JSON.parse(body) });
doc.save(function(err){
if(err) {
console.log(err);
} else {
console.log(body);
}
});
res.writeHead(200, {'Content-Type':'application/json; charset=utf-8'});
res.end('{"result":"ok"}');
});
}
}).listen(1337, "localhost");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment