Ror*_*ory 5 mongoose mongodb node.js mongodb-query
我在node.js中构建一个使用mongodb和mongoose的API.目前我在嵌入式文档(Schema中的Schema)中有一个嵌入式文档,它根本没有持久存储到数据库中,我已尽力而为但没有运气.
我在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: "" }
});
Run Code Online (Sandbox Code Playgroud)
我执行的代码如下:
// 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);
});
});
Run Code Online (Sandbox Code Playgroud)
我可以毫无问题地创建包含评论的博客帖子,但出于某种原因,我无法在评论中创建子评论.Blog Post文档实际上在执行期间打印到控制台时附加了注释和子注释 - 只有它不保存到数据库(它保存带有注释的Blog Post,但没有子注释).
我试图在comments数组上"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'"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2593 次 |
最近记录: |