从dynamic模式获取数据

我正在使用mongoose / nodejs从mongodb获取数据作为json。 为了使用mongoose,我需要像这样先定义模式

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'); }); 

然后在代码中,我可以从数据库中获取数据

 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); }); 

如何为这样的复杂数据定义scheme,可以看到subSection可以进入更深层次。

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

从Mongoose文档 :

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

注意Comment是如何定义为Schema ,然后在Post.comments数组中Post.comments

你的情况有点不同:你有一个我没有尝试过的自引用Schema,但它看起来像这样:

 var sectionSchema = new Schema({ title: String ,subSections: [sectionSchema] }); mongoose.model('Section', sectionSchema); 

然后你可以像这样添加子节点:

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

让我知道这是如何解决的。