对不起,如果标题混淆了,我很难用一个问题来总结这个问题。我目前正在实现一个非常通用的文章发布/阅读web应用程序的评论系统使用平均堆栈。
目前,我为Author、Article和Comment建立了如下模型(省略了与createdBy无关的字段):
var AuthorSchema = new Schema({
// removing unnecessary fields
articles: [{
type: Schema.ObjectId,
ref: 'Article'
}],
comments: [{ // want to find all of a users comments quickly
type: Schema.ObjectId,
ref: 'Comment'
}]
...
}
var CommentSchema = new Schema({
// removing unnecessary fields
content: {
type: String
},
author: { // I want to be able to find a comment's author quickly
type: Schema.ObjectId,
ref: 'Author'
},
...
}
var ArticleSchema = new Schema({
content: {
type: String
},
author: {
type: Schema.ObjectId,
ref: 'Author'
},
comments: [{
type: Schema.ObjectId,
ref: 'Comment'
}]
...
}下面是我在注释控制器中创建注释的代码:
commentCtrl.createComment = function(req, res, next) {
var comment = new Comment(req.body);
if (req.user) {
comment.author = req.user;
// the desired article is stored on the req object by earlier middleware
req.article.comments.unshift(comment); // naive way to add comment
req.article.save(
function(err) {
if (err) {
return sendError(res, 400, getErrorMessage(err));
} else {
Author.findByIdAndUpdate(
req.user._id,
{$push: {comments: comment}},
function(err){
res.json(comment);
}
)
}
});
}
else {
return sendError(res, 401,'The user is not logged in.');
}
};所以现在奇怪的是。作者正确地将注释存储在注释数组字段中,而文章没有。执行后,这里有一篇文章的控制台日志,其中引用了作者(同样,为了清晰起见,我删除了不相关的字段):
{ _id: 56a7b5028bffef9e1ba58ab4,
author:
{ _id: 56a7b1791a5f728c1bb1ee99,
username: 'xTest1',
comments:
[ 53a78291a5f728c1bbcef9b ],
articles:
[ 53a78291a5f728c1bbcef9a ],
},
title: 'Test article',
content: '...',
comments: []
}我最初的想法是,我将注释撤消到注释数组的天真方法不起作用,因此,虽然我已经在req对象上拥有了文章对象,但我更改了实现,以模仿似乎正在更新作者的代码:
Article.findByIdAndUpdate(
req.article._id,
{$push: {comments: comment}},
function(err){ ... // same inner function as above (to update author)
}
}一点都没改变。我没有收到任何错误消息(这是有意义的,因为内部回调工作正常),所以我不知道发生了什么。
发布于 2016-01-27 19:44:18
我发现了问题,我觉得有点傻。希望通过回答我自己的问题,我能防止别人犯同样的错误。
我没有在数据库中创建注释文档。我只是在应用程序中创建一个注释,然后在作者和文章文档中存储对它的引用(或者说,尝试)。
解决方案是首先将注释保存在db中,然后在成功的回调函数中执行原始代码。
有一件事我不明白,那就是为什么它在Author对象中成功地存储了一个引用?如果有人对此有想法的话,它可能会揭示一些我无法预见的休眠问题。
https://stackoverflow.com/questions/35043129
复制相似问题