coure2011
coure2011

Reputation: 42424

getting data from dynamic schema

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'} 
        ]
    }]
  },
  ..
]

Upvotes: 1

Views: 661

Answers (1)

talentedmrjones
talentedmrjones

Reputation: 8111

From the Mongoose documentation:

var Comment = new Schema({
    body  : String
  , date  : Date
});

var Post = new Schema({
    title     : String
  , comments  : [Comment]
});

Notice how Comment is defined as a Schema, and then referenced in the array Post.comments

Your case is a bit different: you have a self-referencing Schema which I have not tried but it would look something like this:

var sectionSchema = new Schema({
  title: String
  ,subSections: [sectionSchema]
});

mongoose.model('Section', sectionSchema);

Then you could add subSections like so:

var section = new mongoose.model('Section');
section.subSections.push({title:'My First Subsection'})

Let me know how that works out.

Upvotes: 1

Related Questions