-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseedScript.js
More file actions
34 lines (27 loc) · 945 Bytes
/
Copy pathseedScript.js
File metadata and controls
34 lines (27 loc) · 945 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import "dotenv/config.js";
import mongoose from "mongoose";
import { categories, products } from "./seedData.js";
import { Category, Product } from "./src/models/index.js";
async function seedDatabase() {
try {
await mongoose.connect(process.env.MONGO_URI);
await Product.deleteMany({});
await Category.deleteMany({});
const categoryDocs = await Category.insertMany(categories);
const categoryMap = categoryDocs.reduce((map, category) => {
map[category.name] = category._id;
return map;
}, {});
const productWithCategoryIds = products.map((product) => ({
...product,
category: categoryMap[product.category],
}));
await Product.insertMany(productWithCategoryIds);
console.log("Database seeding completed successfully.✅");
} catch (error) {
console.error("Error seeding the database: ❌", error);
} finally {
mongoose.connection.close();
}
}
seedDatabase()