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:
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();
respond(req, res, item[0].comments, next);
});
});
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();
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");
...
Posts.comments.markModified("subcomments");