如何更新mongooseembedded式文档中的embedded式文档?

我在使用mongodb和mongoose的node.js中构build一个API。 目前,我在embedded式文档(模式中的模式)内embedded了一个文档,这个文档根本就没有保存到数据库中,而且我尽我所能,但没有运气。

我有用mongoose定义的模式:

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

我可以用没有问题的评论创build博客post,但由于某种原因,我无法在评论上创build子评论。 “博客文章”文档实际上在执行期间向控制台打印时附带了注释和子注释,只是它不会保存到数据库(它会将博客文章保存为注释,但不包含子注释)。

我试图在评论数组上“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'" 

问题自解决。 亚伦·赫克曼(Aaron Heckmann)给出了关于mongooseGoogle集团的答案:

在将它们传递给父模式之前,总是声明你的子模式,否则你传递未定义的模式。

SubCommentSchema应该是第一个,然后是Comment和BlogPost。

反转了它的工作模式。

我更新文件不是一个重要的问题,因为embedded式文件也完全有能力提供任何服务。