2012-03-20 2 views
1

mongoose/nodejs를 사용하여 mongodb에서 json으로 데이터를 가져옵니다. 몽구스을 사용하기 위해 내가 다음 코드에서이 같은 복잡한 데이터 구조를 정의하는 방법 DB 동적 스키마에서 데이터 가져 오기

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

같은 데이터를 얻을 수있는이

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

처럼 첫번째 스키마를 정의해야합니다, 당신은 것을 볼 수있다 subSection은 더 깊은 레벨로 갈 수 있습니다. the Mongoose documentation에서

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

몽구스에 익숙하지 않지만이 스레드가 관심을 가질 수 있습니다 : https://groups.google.com/forum/?fromgroups#!topic/mongoose-orm/0yUVXNyprx8. – Ren

답변

1

: CommentSchema로 정의하고 배열에서 참조하는 방법을

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

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

공지 사항 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'}) 

나 그 밖으로 작동하는 방법을 알려주세요.