I want to add multiple comments to my Article (mongoose)
You are currently in callback hell and using async/await
willl go a long way making your code readable and thus makes it easy to debug.
Consider the following workflow that uses 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) }}
You can pass an array of documents to Model.create
, just create comments
first then use Array.map
to create a new array from articletData
with comments
assigned to each article
using async/await
:
async function seedDB() { ... const comments = await Comment.create(commentData); const articles = await Article.create(articleData.map(article => { article.comments = comments; return article })); ...
using Promise.then()
:
function seedDB() { ... Comment.create(commentData).then(comments => Article.create(articleData.map(article => { article.comments = comments; return article })).then(articles => { }); }); ...
When you first Article.create...
, on successfull creation the function returns the article object or a error on the other side.
You need to run the forEach loop in the newly created article for achieve each article contain the Comments.
you need to work with the existed newly created article data.
Example
articleData.forEach(function (article) { Article.create(article, function (err, article) { if (err) { console.log(err); } else { article.update( { "_id": ObjectId(article.id) }, { $push: { comments: commentData } } ); // OR try something like // article.comments = commentData // OR // article.comments.insert(commentData) article.save(); } });});