-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed.js
36 lines (31 loc) · 1.33 KB
/
seed.js
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
35
36
const mongoose = require('mongoose');
// Import the models
const Product = require('./models/Product');
const User = require('./models/User');
// Import the objects that contains the data
const products = require('./seeds/products');
const users = require('./seeds/users');
// Instantiate each object of our array in the model
const productsDocuments = products.map(product => new Product(product));
const usersDocuments = users.map(user => new User(user));
// Connect to the database to perform the necessary actions
mongoose.connect(process.env.DB_URL || 'mongodb://localhost:27017/ecommerce', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(async () => {
// Obtain the existing products and users from the database
const allProducts = await Product.find();
const allUsers = await User.find();
// If exists, drop the collection
if (allProducts.length && allUsers.length) {
await Product.collection.drop();
await User.collection.drop();
}
}).catch((err) => console.log(`Error deleting data: ${err}`))
.then(async () => {
// Fill the database with the new array
await Product.insertMany(productsDocuments);
await User.insertMany(usersDocuments);
}).catch((err) => console.log(`Error creating data: ${err}`))
// Disconnect from the database
.finally(() => mongoose.disconnect());