// Step 1: Import the required modules
const mongoose = require('mongoose');
// Step 2: Set up the MongoDB connection string
const connectionString = 'mongodb://localhost:27017/your_database_name';
// Step 3: Connect to the MongoDB database
mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
// Step 4: Get the default connection
const db = mongoose.connection;
// Step 5: Set up event listeners for the MongoDB connection
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to the MongoDB database');
});
// Step 6: Create a Mongoose schema (optional)
const exampleSchema = new mongoose.Schema({
name: String,
age: Number
});
// Step 7: Create a Mongoose model using the schema (optional)
const ExampleModel = mongoose.model('Example', exampleSchema);
// Step 8: Use the model to interact with the MongoDB database (optional)
const exampleInstance = new ExampleModel({
name: 'John Doe',
age: 25
});
exampleInstance.save((err) => {
if (err) return console.error(err);
console.log('Document saved to the database');
});