Connecting a Node.js application to MongoDB is crucial for data persistence. This tutorial will guide you through setting up MongoDB, installing dependencies, and writing a connection script using Mongoose.
Node.js MongoDB Connection
1. Install MongoDB and Mongoose
Ensure MongoDB is installed on your system. Install Mongoose, an ODM (Object Data Modeling) library, for easier MongoDB interactions.
npm install mongoose
2. Setup MongoDB Connection
Create a file named db.js
and establish a connection to MongoDB using Mongoose.
const mongoose = require('mongoose');
const mongoURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));
3. Define a Mongoose Schema and Model
Create a model for structured data storage.
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
module.exports = User;
4. Insert and Fetch Data
Use Mongoose methods to insert and retrieve data from MongoDB.
const User = require('./userModel');
// Insert a user
const newUser = new User({ name: 'John Doe', email: 'john@example.com', age: 30 });
newUser.save()
.then(user => console.log('User saved:', user))
.catch(err => console.error('Error saving user:', err));
// Fetch users
User.find()
.then(users => console.log('Users:', users))
.catch(err => console.error('Error fetching users:', err));
5. Conclusion
By following these steps, you can successfully connect a Node.js application to MongoDB and perform database operations using Mongoose.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.