Introduction
MongoDB is a popular NoSQL database, and Mongoose is a powerful library that simplifies working with MongoDB in Node.js. This guide will show you how to connect to MongoDB using Mongoose, create a schema, and perform basic database operations in JavaScript.
What is Mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a schema-based solution to model data and includes built-in data validation, type casting, and query building.
Prerequisites
- Node.js installed on your system
- Basic understanding of JavaScript
- MongoDB installed locally or access to a MongoDB Atlas cluster
Step 1: Setting Up the Project
First, create a new Node.js project and install Mongoose:
- Initialize a new Node.js project:bashCopy code
mkdir mongoose-demo cd mongoose-demo npm init -y
- Install Mongoose:bashCopy code
npm install mongoose
Step 2: Connecting to MongoDB
You can connect to a local MongoDB instance or a MongoDB Atlas cluster. For this example, we'll connect to a local instance:
javascriptCopy codeconst mongoose = require('mongoose');
async function connectDB() { try { await mongoose.connect('mongodb://127.0.0.1:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }); console.log('Connected to MongoDB'); } catch (error) { console.error('Error connecting to MongoDB:', error); } }
connectDB();
Replace 'mongodb://127.0.0.1:27017/mydatabase'
with your MongoDB connection string if you're using MongoDB Atlas.
Step 3: Creating a Mongoose Schema
A schema defines the structure of your documents, default values, and data types. Let's create a simple schema for a User
model:
javascriptCopy codeconst userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: { type: Number, min: 0 }, createdAt: { type: Date, default: Date.now } });
// Creating a model from the schema const User = mongoose.model('User', userSchema);
In this example:
name
andemail
are required fields.email
is unique.age
has a minimum value of 0.createdAt
is set to the current date by default.
Step 4: Using the Schema to Interact with MongoDB
Now, let's perform some basic operations like creating, reading, updating, and deleting documents.
4.1 Creating a New User
javascriptCopy codeasync function createUser() { try { const user = new User({ name: 'John Doe', email: '[email protected]', age: 30 }); const savedUser = await user.save(); console.log('User created:', savedUser); } catch (error) { console.error('Error creating user:', error); } }
createUser();
4.2 Reading Users
javascriptCopy codeasync function getUsers() { try { const users = await User.find(); console.log('Users:', users); } catch (error) { console.error('Error fetching users:', error); } }
getUsers();
4.3 Updating a User
javascriptCopy codeasync function updateUser(userId) { try { const updatedUser = await User.findByIdAndUpdate(userId, { age: 31 }, { new: true }); console.log('User updated:', updatedUser); } catch (error) { console.error('Error updating user:', error); } }
// Example usage // updateUser('60c72b2f9f1b8e1e7c8f9e1d');
4.4 Deleting a User
javascriptCopy codeasync function deleteUser(userId) { try { const deletedUser = await User.findByIdAndDelete(userId); console.log('User deleted:', deletedUser); } catch (error) { console.error('Error deleting user:', error); } }
// Example usage // deleteUser('60c72b2f9f1b8e1e7c8f9e1d');
Conclusion
Connecting MongoDB with JavaScript using Mongoose makes working with the database easier by providing a schema-based solution. With Mongoose, you can easily create and manage data models, validate data, and interact with MongoDB using simple and expressive code.