How to update an embedded document in an embedded document in mongoose?

I am creating an API in node.js that uses mongodb and mongoose. Currently, I have an embedded document in an embedded document (the diagram inside the diagram), which simply is not stored in the database, and I tried everything I could, but no luck.

I have a schema defined in mongoose as:

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

And the code that I execute looks like this:

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

I can create blogs with comments without any problems, but for some reason I cannot create attachments in comments. The Post Blog document actually has comments and subcomponents attached when printing to the console at run time - only it is not saved in the database (it saves a blog post with a comment, but without subcomponents).

"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'"
+5
2

. mongoose Google Group:

, undefined.

SubCommentSchema , , BlogPost.

.

+6

, , .

0

All Articles