Mongoose is a powerful MongoDB object modeling library for Node.js enabling you to easily interact between your Node.js app and MongoDB. In this article we are going to explore how you can connect your Node.js app to MongoDB using MongooseJS. You will learn how to create a connection, specify schemas, and perform CRUD operations with MongoDB efficiently.
What is MongooseJS?MongooseJS is an Object Data Modeling library for Node.js and MongoDB. It provides a lightweight API for accessing MongoDB databases, data modeling based on schema, and powerful query building and validation. Mongoose simplifies working with MongoDB in an asynchronous environment and makes defining and manipulating documents easy.
Steps to connect MongoDB with Node AppBelow are the steps to establish MongoDB with a Node.js application through MongooseJS:
Step 1. Install MongoDBInstall MongoDB on your local system or take advantage of a cloud MongoDB service such as MongoDB Atlas to host your databases with ease. For local setups, refer to the official MongoDB documentation.
Step 2. Create a Node.js ApplicationInitialize a new Node.js application by running a new project using npm (Node Package Manager) and creating relevant dependencies.
mkdir my-node-appStep 3. Install MongooseJS
cd my-node-app
npm init -y
Use npm to install MongooseJS in your Node.js project. MongooseJS allows you to interact with MongoDB from Node.js using an easy-to-use API.
npm install mongooseFolder Structure: Folder Strucutre
Updated Dependencies:
Updated Dependencies Step 4. Connect to MongoDBIn your Node.js application, establish a connection to your MongoDB database using MongooseJS. This typically involves specifying the MongoDB connection URI and handling connection events.
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose
.connect('mongodb://localhost:27017/mydatabase',
{
useNewUrlParser: true,
useUnifiedTopology: true
});// Handle connection events
const db = mongoose.connection;
db
.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
Make sure to replace '
mongodb://localhost:27017/mydatabase
'
with your actual MongoDB URI if using a cloud database like MongoDB Atlas.
Define Mongoose schema to specify the structure of your MongoDB documents. This includes defining fields, types, validations, and other options.
const { Schema } = mongoose;Step 6. Perform CRUD Operationsconst userSchema = new Schema({
name: String,
email: { type: String, required: true, unique: true },
age: Number
});const User = mongoose.model('User', userSchema);
With MongooseJS, you can easily perform CRUD (Create, Read, Update, Delete) operations on your MongoDB database using Mongoose models.
// Create a new userStep 7. Close MongoDB Connection
const newUser = new User({ name: 'John', email: 'john@example.com', age: 30 });
newUser.save()
.then(() => console.log('User created'))
.catch(err => console.error(err));// Find users
User.find({ age: { $gte: 25 } })
.then(users => console.log('Users:', users))
.catch(err => console.error(err));// Update a user
User.updateOne({ _id: 'user_id' }, { age: 35 })
.then(() => console.log('User updated'))
.catch(err => console.error(err));// Delete a user
User.deleteOne({ _id: 'user_id' })
.then(() => console.log('User deleted'))
.catch(err => console.error(err));
Close the MongoDB connection when your Node.js application terminates or shuts down gracefully.
// Close MongoDB connection
mongoose.connection.close(() => {
console.log('Disconnected from MongoDB');
});
By doing so, you will be able to integrate MongoDB with your Node.js application using MongooseJS such that you are able to write and read data in MongoDB in an efficient and structured way.
Example: Full Node.js Application Connecting to MongoDBHere’s a full example of connecting MongoDB with a Node.js app using Mongoose and performing basic CRUD operations:
// index.js file
const mongoose = require('mongoose');// Connect to MongoDB
mongoose.connect('database URI', {
useNewUrlParser: true,
useUnifiedTopology: true
});const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');// Define Mongoose schema
const userSchema = new mongoose.Schema({
name: String,
email: { type: String, required: true, unique: true },
age: Number
});const User = mongoose.model('User', userSchema);
// Perform CRUD operations
// Create a new user
const newUser = new User({ name: 'John', email: 'john@example.com', age: 30 });
newUser.save()
.then(() => {
console.log('User created');// Find users with age >= 25
return User.find({ age: { $gte: 25 } });
})
.then(users => {
console.log('Users:', users);// Assuming you have a valid ObjectId for the user you want to update
const userIdToUpdate = '6123456789abcdef01234567'; // Replace with actual ObjectId
return User.updateOne({ _id: userIdToUpdate }, { age: 35 });
})
.then(() => {
console.log('User updated');// Assuming you have a valid ObjectId for the user you want to delete
const userIdToDelete = '6123456789abcdef01234567'; // Replace with actual ObjectId
return User.deleteOne({ _id: userIdToDelete });
})
.then(() => {
console.log('User deleted');// Close MongoDB connection
mongoose.connection.close();
})
.catch(err => console.error(err));
});
Output:
MongoDB connectionExplanation: The application will display the process of creating, reading, updating, and deleting user documents. Once the CRUD operations are done, the app closes the MongoDB connection.
ConclusionThrough the above steps, you can successfully integrate MongoDB with your Node.js application using Mongoose. This strong integration allows you to deal with your MongoDB database in an easy and systematic manner. With in-built features of Mongoose like validation, schema definition, and CRUD operations, developing robust and scalable MongoDB-based applications is convenient.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4