Repository navigation
Expand file tree
/
Copy pathseed.js
More file actions
64 lines (59 loc) · 1.47 KB
/
Copy pathseed.js
File metadata and controls
64 lines (59 loc) · 1.47 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// seed.js
const mongoose = require('mongoose');
const User = require('./models/usermodel'); // Import the user model
require('dotenv').config(); // Load environment variables from .env file
// Connect to the MongoDB database
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to MongoDB...');
})
.catch((err) => {
console.error('Failed to connect to MongoDB', err);
process.exit(1); // Exit the process with a failure code
});
// Dummy user data
const users = [
{
name: 'John Doe',
email: 'john@example.com',
phone: '1234567890',
password: 'password123',
age: 30,
gender: 'Male',
},
{
name: 'Jane Smith',
email: 'jane@example.com',
phone: '0987654321',
password: 'password456',
age: 28,
gender: 'Female',
},
{
name: 'Sam Brown',
email: 'sam@example.com',
phone: '1122334455',
password: 'password789',
age: 35,
gender: 'Male',
},
];
// Function to seed the database
const seedDatabase = async () => {
try {
// Clear the existing data (optional)
await User.deleteMany();
// Insert new users
await User.insertMany(users);
console.log('Database seeded successfully!');
mongoose.connection.close(); // Close the connection
} catch (err) {
console.error('Error seeding database:', err);
mongoose.connection.close(); // Close the connection on error
}
};
// Call the seed function
seedDatabase();