getting data from dynamic schema

Posted by coure2011 on Stack Overflow See other posts from Stack Overflow or by coure2011
Published on 2012-03-20T12:08:30Z Indexed on 2012/03/20 17:29 UTC
Read the original article Hit count: 240

Filed under:
|
|

I am using mongoose/nodejs to get data as json from mongodb. For using mongoose I need to define schema first like this

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var GPSDataSchema = new Schema({
    createdAt: { type: Date, default: Date.now }
    ,speed: {type: String, trim: true}
    ,battery: { type: String, trim: true }
});

var GPSData = mongoose.model('GPSData', GPSDataSchema);
mongoose.connect('mongodb://localhost/gpsdatabase');
var db = mongoose.connection;
db.on('open', function() {
    console.log('DB Started');
});

then in code I can get data from db like

GPSData.find({"createdAt" : { $gte : dateStr, $lte:  nextDate }}, function(err, data) {

            res.writeHead(200, {
                    "Content-Type": "application/json",
                    "Access-Control-Allow-Origin": "*"
            });
            var body = JSON.stringify(data);
            res.end(body);
        });

How to define scheme for a complex data like this, you can see that subSection can go to any deeper level.

[
  {
    'title': 'Some Title',
    'subSection': [{
       'title': 'Inner1',
       'subSection': [
          {'titile': 'test', 'url': 'ab/cd'} 
        ]
    }]
  },
  ..
]

© Stack Overflow or respective owner

Related posts about node.js

Related posts about mongodb