9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでHTTP POSTのbodyをスキーマレスにMongoDBに格納

Posted at

node.jsでMongoDBを扱うには mongoose をつかうとすごく楽です。しかし、mongooseを使う際にはスキーマを定義しなければいけません。HTTP POSTのbody(JSON形式)のように何が飛んでくるか分からない場合にもスキーマレスにとりあえず突っ込んでおきたいというときには、Schema.Types.Mixed という型を指定してスキーマを作成すれば、何でも格納でき、JSONデータもそのまま格納できます。

環境

  • OS: OS X 10.9.4
  • node.js: v0.10.32
  • mongoose: v3.8.18
  • MongoDB: v2.6.4

下準備:mongooseがなければ、npmでインストールできます。

$ npm install mongoose

ソース

postreceive-mongo.js
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");

node.js file which saves body of HTTP POST to Mong ...

ただし、これだと "data" というキーの値としてJSONデータが格納されるため、階層が1段深くなってしまいます。それが嫌だという方は、mongo driverを使う方法もあるようです。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?