【发布时间】:2012-05-11 06:59:30
【问题描述】:
我正在使用 mongodb 和 mongoose 在 node.js 中构建一个 API。目前,我在嵌入文档(架构中的架构)中有一个嵌入文档,它根本没有保存到数据库中,我已经尽我所能但没有运气。
我在 mongoose 中将 Schema 定义为:
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);
});
});
我可以毫无问题地使用 cmets 创建博客帖子,但由于某种原因,我无法在评论上创建子 cmets。博客文章文档实际上在执行期间打印到控制台时附加了 cmets 和 subcmets - 只是它不保存到数据库中(它保存带有评论的博客文章,但没有子 cmets)。
我曾尝试在 cmets 数组上“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 中转换对象?因为它可能无法将评论和子评论识别为猫鼬文档?
标签: node.js mongodb mongoose mongodb-query