gpt4 book ai didi

javascript - 我想在我的文章中添加多个评论( Mongoose )

转载 作者:行者123 更新时间:2023-12-04 10:42:04 25 4
gpt4 key购买 nike

我正在创建一个网站,我想播种一些数据。

我想创建两篇文章,每篇文章有两条评论:

var mongoose = require("mongoose"),
Article = require("./models/articles.js"),
Comment = require("./models/comments.js");

var articleData = [
{
title: "Fast Cars",
author: "Steve Novak",
company: "AthLead",
body: "SOME TEXT"
},
{
title: "New Design",
author: "Kevin Garnett",
company: "Revoos",
body: "COOL ARTICLE"
}
];

var commentData = [
{
body: "I really love the new design",
author: "Mark Cuban"
},
{
body: "This is hitting my funny bone",
author: "Lisa Jones"
}
];


我正在删除所有过去的评论和文章。

然后对于每篇文章,我首先创建文章,然后推送两条评论。

我在将新形成的文章保存到数据库时遇到问题:

将 article.save() 放在 1. 导致并行 save() 错误发生

而放置在 2. 导致没有评论被保存。

function seedDB() {
Comment.deleteMany({}, function (err) {
if (err) {
console.log(err);
}
Article.deleteMany({}, function (err) {
if (err) {
console.log(err);
}

articleData.forEach(function (article) {
Article.create(article, function (err, article) {
if (err) {
console.log(err);
} else {
commentData.forEach(function(comment) {
Comment.create(comment, function (err, comment) {
if (err)
console.log(err);
else {
article.comments.push(comment);
// PROBLEM
// 1. article.save();
}

})
})
// PROBLEM
//2. article.save();
}
});
});

});


});
});

console.log("Database Reset");
}



module.exports = seedDB;

最佳答案

您目前在 callback hell并使用 async/await将大大提高您的代码可读性,从而使调试变得容易。

考虑以下使用 async/await 的工作流

async function seedDB() {
try {
// clean up all comments
await Comment.deleteMany({}).exec()

// clean up all articles
await Article.deleteMany({}).exec()

// create articles
await Article.create(articleData)

// create comments
const comments = await Comment.create(commentData)

// update articles with the new comments
const updatedArticles = await Article.updateMany(
{},
{ '$set': { comments } }
).exec()

console.log(updatedArticles)

} catch (err) {
console.error(err)
}
}

关于javascript - 我想在我的文章中添加多个评论( Mongoose ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875530/

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