forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig MongoDb.js
34 lines (28 loc) · 931 Bytes
/
config MongoDb.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
const mongoose = require('mongoose');
// MongoDB connection URL (replace with your own URL)
const dbUrl = 'mongodb://localhost/mydatabase';
// Define a Mongoose schema
const userSchema = new mongoose.Schema({
username: String,
email: String,
});
// Create a Mongoose model based on the schema
const User = mongoose.model('User', userSchema);
// Establish the connection and define error handling
mongoose.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
// Error handling and close on exit
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('MongoDB connection closed through app termination');
process.exit(0);
});
});