2012-03-20 71 views
1

我使用mongoose/nodejs从mongodb获取数据作为json。对于使用猫鼬我需要首先定义模式这样从动态模式获取数据

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

如何定义这样一个复杂的数据方案得到的数据,你可以看到, subSection可以进入更深层次。

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

我对Mongoose不是很熟悉,但是这个主题可能会让你感兴趣:https://groups.google.com/forum/?fromgroups#!topic/mongoose-orm/0yUVXNyprx8。 – Ren 2012-03-20 14:42:19

回答

1

the Mongoose documentation

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

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

通知Comment是如何被定义为Schema,然后在阵列中引用Post.comments

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

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

让我知道它是如何工作的。