-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
48 lines (42 loc) · 1.21 KB
/
Copy pathdatabase.js
File metadata and controls
48 lines (42 loc) · 1.21 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
const mongoose = require("mongoose");
const User = require("./models/User");
// Connect to MongoDB
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGODB_URI);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.error("MongoDB connection error:", error);
process.exit(1);
}
};
// Initialize database with default admin user
const initDatabase = async () => {
try {
// Check if admin user exists
const adminExists = await User.findOne({ username: "admin" });
if (!adminExists) {
// Create default admin user
const adminUser = new User({
username: "admin",
email: "admin@inventory.com",
password: "admin123", // Will be hashed by the pre-save hook
role: "admin",
});
await adminUser.save();
console.log(
"Default admin user created (username: admin, password: admin123)"
);
} else {
console.log("Admin user already exists");
}
console.log("Database initialized successfully");
} catch (error) {
console.error("Database initialization error:", error);
throw error;
}
};
module.exports = {
connectDB,
initDatabase,
};