'I create some document to mongoose but not showing
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
Solution 1:[1]
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}`));
}));
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Navoneel Talukdar |
Solution 2 | Jackson |