2012-05-01 9 views
5

mongodb와 mongoose를 사용하는 node.js에 API를 구축하고 있습니다. 현재 데이터베이스에 포함되지 않은 임베디드 문서 (스키마 내의 스키마)에 임베드 된 문서가 있습니다.몽구스로 임베디드 문서 내의 임베디드 문서를 업데이트하는 방법은 무엇입니까?

내가 가지고있는 스키마의 몽구스에 정의 :

var BlogPostSchema = new Schema({ 
    creationTime: { type: Date, default: Date.now }, 
    author: { type: ObjectId, ref: "User" }, 
    title: { type: String }, 
    body: { type: String }, 
    comments: [CommentSchema] 
}); 

var CommentSchema = new Schema({ 
    creationTime: { type: Date, default: Date.now }, 
    user: { type: ObjectId, ref: "User" }, 
    body: { type: String, default: "" }, 
    subComments: [SubCommentSchema] 
}); 

var SubCommentSchema = new Schema({ 
    creationTime: { type: Date, default: Date.now }, 
    user: { type: ObjectId, ref: "User" }, 
    body: { type: String, default: "" } 
}); 

다음과 같이 내가 실행 코드는 다음과 같습니다

// Create a comment 
app.post("/posts/:id/comments", function(req, res, next) { 
    Posts.find({ _id : req.params.id }, function(err, item){ 
    if(err) return next("Error finding blog post.");     
    item[0].comments.push(new Comment(JSON.parse(req.body))); 
    item[0].save(); // <= This actually saves and works fine 
    respond(req, res, item[0].comments, next); 
    }); 
}); 

// Create a subcomment 
app.post("/posts/:id/comments/:commentid/subcomments", function(req, res, next) { 
    Posts.find({ _id : req.params.id }, function(err, item){ 
    if(err) return next("Error finding blog post."); 
    item[0].comments[req.params.commentid - 1].subcomments.push(new SubComment(JSON.parse(req.body))); 
    item[0].save(); // <= This completes (without error btw) but does not persist to the database 
    respond(req, res, item[0].comments[req.params.commentid - 1].subcomments, next); 
    }); 
}); 

내가 문제없이 의견 블로그 게시물을 만들 수 있지만 몇 가지 이유 나는 코멘트에 부제를 만들 수 없다. 블로그 포스트 문서는 실제로 실행 중에 콘솔에 인쇄 할 때 주석과 부제를 첨부합니다 - 데이터베이스에만 저장하지 않습니다 (주석이있는 블로그 게시물을 저장하지만 부제는 저장하지 않습니다). 내가 코멘트 배열의 "markModified"을 시도

,하지만 변화 : 포함 된 문서는 어떤 서비스를 완벽하게 할 수있는 등 문서의 갱신이 중요한 문제가되지 않습니다

Posts.markModified("comments"); // <= no error, but also no change 
... 
Posts.comments.markModified("subcomments"); // <= produces an error: "TypeError: Object [object Object] has no method 'markModified'" 
+0

MongoDB에서 객체를 어떻게 든 던져야 할 수도 있습니다. 논평과 부제를 몽구스 문서로 인정하지 않을 수도 있습니다. – Rory

답변

6

문제가 해결되었습니다. 나는 mongoose Google Group에 아론 HECKMANN으로 대답을 넘겨되었다

항상 그렇지 않으면 당신은 정의되지 않은 전달하는 당신 부모 스키마에 전달하기 전에 아이의 스키마를 선언합니다.

SubCommentSchema가 먼저오고 그 다음에 BlogPost가 이어져야합니다.

스키마를 역전시킨 후에도 효과가있었습니다.

0

I 일 .

+1

흠, 다소 수수께끼 같은. 당신이하고 싶은 말에 대해 좀 더 자세히 설명해 주시겠습니까? – Rory