-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateAdmin.js
More file actions
36 lines (31 loc) · 1.07 KB
/
createAdmin.js
File metadata and controls
36 lines (31 loc) · 1.07 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
const bcrypt = require('bcryptjs');
const { connectDB, client } = require('./mongoClient');
async function createAdmin(email, plainPassword) {
try {
await connectDB();
const db = client.db('portfolio'); // Replace with your database name
const collection = db.collection('admins');
// Hash the password
const hashedPassword = await bcrypt.hash(plainPassword, 10);
// Insert into MongoDB
const result = await collection.insertOne({ email, password: hashedPassword });
// Check if the insertion was successful
if (result.insertedId) {
console.log('✅ Admin created with ID:', result.insertedId);
return { _id: result.insertedId, email, password: hashedPassword };
} else {
throw new Error('Failed to create admin: No inserted ID returned');
}
} catch (error) {
console.error('❌ Error creating admin:', error.message);
throw error;
}
}
// Example usage
(async () => {
try {
await createAdmin('admin@example.com', 'admin123');
} catch (error) {
console.error('Failed to create admin:', error);
}
})();