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'"
MongoDB에서 객체를 어떻게 든 던져야 할 수도 있습니다. 논평과 부제를 몽구스 문서로 인정하지 않을 수도 있습니다. – Rory