Loading...
Loading...

Node.js MongoDB Connection

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.

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.

0 Interaction
649 Views
Views
42 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home