skip to Main Content

I tried to create 5 documents in mondoDB , and I’m sure that I successfully created 5 documents.

But it only shows one document on Robo3T.

Here is my code

const Category = require('../category')

const db = require('../../config/mongoose')
const categoryList = require('./categoryList.json')

db.once('open', () => {

  return Promise.all(Array.from({ length: 5 }, (_, index) => {
      Category.create({ 
        name: categoryList[index].name,
        icon: categoryList[index].icon
      })
  }))

    .then(() => console.log('categorySeeder.js is done'))
    .then(() => process.exit())
})

And here is my Robo3T
enter image description here

2

Answers


  1. const Category = require('../category')
    
    const db = require('../../config/mongoose')
    const categoryList = require('./categoryList.json')
    
    db.once('open', async () => {
    
      return Promise.all(Array.from({ length: 5 }, (_, index) => {
          return new Category({ 
            name: categoryList[index].name,
            icon: categoryList[index].icon
          }).save();
          
         // or
          return Category.create({ 
            name: categoryList[index].name,
            icon: categoryList[index].icon
          });
      }))
    
        .then(() => console.log('categorySeeder.js is done'))
        .then(() => process.exit())
    })
    

    Try this

    Login or Signup to reply.
  2. Use aysnc/await

    await Promise.all(Array.from({ length: 5}).map(async (_, index) => {
          let categoryObj = new Category({ name: categoryList[index].name, icon: categoryList[index].icon });
          categoryObj.save().then(res => console.log(`Created book ${res}`));
    }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search