Learn how to connect nodejs with mongo db
Hello dear, today we learn, how to connect nodejs with Mongodb
To connect, we can use the official MongoDB Node.js driver or an ODM (Object Data Modeling) library like Mongoose. Here's how we can connect Node.js with MongoDB using both approaches:
Using the Official MongoDB Node.js Driver:
1. Install the MongoDB Node.js Driver:
- npm install MongoDB
2. Connect to MongoDB:
// Import the required module in node.js application
const { MongoClient } = require('mongodb');
// Connection URI in nodejs
const uri = 'mongodb://localhost:27017/mydatabase';
// Create a new MongoClient
const client = new MongoClient(uri);
// Connect to MongoDB
async function connect() {
try {
await client.connect();
console.log('Connected to MongoDB');
// You can now perform database operations using client.db()
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}
// Call the connect function
connect();
3. Perform Database Operations: we can now perform various database operations using the client.db() object returned by connect().
Using Mongoose (ODM Library):
1. Install Mongoose:
npm install mongoose
2. Connect to MongoDB using Mongoose:
const mongoose = require('mongoose');
// Connection URI
const uri = 'mongodb://localhost:27017/mydatabase';
// Connect to MongoDB
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
// Check connection status
const db = mongoose.connection; db.on('error', console.error.bind(console, 'Connection error:')); db.once('open', () => { console.log('Connected to MongoDB');
// we can now define and use Mongoose models });
3. Define Mongoose Models:
const { Schema } = mongoose;
// Define a schema
const userSchema = new Schema({
name: String,
email: String,
age: Number
});
//Now Define a model
const User = mongoose.model('User', userSchema);
// Example usage
const user = new User({
name: 'John',
email: 'johna@examplea.com',
age: 30
}
);
user.save()
.then(() => console.log('User saved successfully'))
.catch(error => console.error('Error saving user:', error));
With both approaches, you'll be able to connect your Node.js application to MongoDB and perform database operations as needed. Choose the approach that best fits your project requirements and preferences.
0 Comments