2012-10-16 3 views
2

내가 잘못하고있는 것을 찾을 수 없다 ... 몽구스 모델에서 하위 문서를 정의하려고하는데 스키마 정의를 다른 파일로 분할하면 하위 모델이 존중되지 않는다.왜 mongoose.model ('Model')입니까? 스키마가 잘못 되었나요?

첫째, 코멘트 스키마를 정의 :

var CommentSchema = new Schema({ 
    "text": { type: String }, 
    "created_on": { type: Date, default: Date.now } 
}); 
mongoose.model('Comment', CommentSchema); 

다음으로, 우리는 지금 부모를 정의하는 다른 파일

var CommentSchema2 = mongoose.model('Comment').Schema; 

에서로드 것이다 (같은) mongoose.model (에서로드하여 다른 스키마를 생성 스키마

var PostSchema = new Schema({ 
    "title": { type: String }, 
    "content": { type: String }, 
    "comments": [ CommentSchema ], 
    "comments2": [ CommentSchema2 ] 
}); 
var Post = mongoose.model('Post', PostSchema); 

그리고 몇 가지 테스트

var post = new Post({ 
    title: "Hey !", 
    content: "nothing else matter" 
}); 

console.log(post.comments); // [] 
console.log(post.comments2); // [ ] // <-- space difference 

post.comments.unshift({ text: 'JOHN' }); 
post.comments2.unshift({ text: 'MICHAEL' }); 

console.log(post.comments); // [{ text: 'JOHN', _id: 507cc0511ef63d7f0c000003, created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) }] 
console.log(post.comments2); // [ [object Object] ] 

post.save(function(err, post){ 

    post.comments.unshift({ text: 'DOE' }); 
    post.comments2.unshift({ text: 'JONES' }); 

    console.log(post.comments[0]); // { text: 'DOE', _id: 507cbecd71637fb30a000003, created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) } // :-) 
    console.log(post.comments2[0]); // { text: 'JONES' } // :'-(

    post.save(function (err, p) { 
     if (err) return handleError(err) 

     console.log(p); 
    /* 
    { __v: 1, 
     title: 'Hey !', 
     content: 'nothing else matter', 
     _id: 507cc151326266ea0d000002, 
     comments2: [ { text: 'JONES' }, { text: 'MICHAEL' } ], 
     comments: 
     [ { text: 'DOE', 
      _id: 507cc151326266ea0d000004, 
      created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) }, 
     { text: 'JOHN', 
      _id: 507cc151326266ea0d000003, 
      created_on: Tue Oct 16 2012 04:07:13 GMT+0200 (CEST) } ] } 
    */ 

     p.remove(); 
    });  
}); 

위에서 볼 수 있듯이 CommentSchema, ids 및 기본 속성이 올바르게 설정되어 있습니다. 하지만로드 된 CommentSchema2는 잘못되었습니다.

'인구'버전을 사용해 보았지만 찾고있는 것이 아닙니다. 다른 컬렉션을 사용하고 싶지 않습니다.

무엇이 잘못되었는지 알고 계십니까? 감사 !

몽구스 v3.3.1

nodejs의 v0.8.12

전체 요점 : https://gist.github.com/de43219d01f0266d1adf

답변

1

모델의 스키마 객체가 Model.schema하지 Model.Schema로 액세스 할 수 있습니다.

var CommentSchema2 = mongoose.model('Comment').schema; 
+0

고마워 :

그래서에 라인 (20) 당신의 요지를 변경! 나는 당신의 눈을 뜨고 "RTFM"부분을 놓쳤다 ... – Balbuzar