gpt4 book ai didi

node.js - 为什么我无法在第一个回调函数中更新此 MongodDB 文档(虽然我可以毫无问题地更新不同的文档)?

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:29 24 4
gpt4 key购买 nike

抱歉,如果标题令人困惑,我很难用一个问题来总结问题。我目前正在使用 MEAN 堆栈为一个非常通用的文章发布/阅读 Web 应用程序实现一个评论系统。

我目前有 AuthorArticleComment 的模型,如下所示(省略了不相关的字段,如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'
}]
...
}

这是我在评论 Controller 中创建评论的代码:

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)
}
}

这根本没有改变任何事情。我没有收到任何错误消息(这是有道理的,因为内部回调工作得很好),所以我不知道发生了什么。

最佳答案

我发现问题了,感觉有点傻。希望通过回答我自己的问题,我可以防止其他人犯同样的错误。

我没有在数据库中创建评论文档。我只是在应用程序中创建一个评论,然后将对其的引用(或者更确切地说,试图)存储在作者和文章文档中。

解决办法是先将Comment保存到db中,然后在成功的回调函数中执行原来的代码。

我无法弄清楚的一件事是为什么它能够成功地将引用存储在 Author 对象中?如果有人对此有想法,它可能会揭示一些我无法预见的潜在问题。

关于node.js - 为什么我无法在第一个回调函数中更新此 MongodDB 文档(虽然我可以毫无问题地更新不同的文档)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com