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
CodePudding user response:
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
CodePudding user response:
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}`));
}));