【问题标题】:How to update an embedded document within an embedded document in mongoose?如何在猫鼬的嵌入式文档中更新嵌入式文档?
【发布时间】: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


【解决方案1】:

我认为文档的更新不是一个重要的问题,因为嵌入的文档也完全能够提供任何服务。

【讨论】:

  • 嗯,有点神秘。你能详细说明你想说什么吗?
【解决方案2】:

问题已解决。 Aaron Heckmann 在mongoose Google Group 上给了我答案:

始终在将子架构传递给父架构之前声明它们,否则您传递的是未定义的。

应该先是 SubCommentSchema,然后是 Comment,然后是 BlogPost。

在反转架构后它起作用了。

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 2015-08-14
    • 2011-10-25
    • 2012-02-15
    • 2015-04-21
    • 2015-09-06
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多