I want to add multiple comments to my Article (mongoose) I want to add multiple comments to my Article (mongoose) mongoose mongoose

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