If you're new to building applications with Node.js and MongoDB, you may be eager to get started with Mongoose—an elegant MongoDB object modeling tool designed to work in an asynchronous environment. With Mongoose, you can define schemas, models, and easily perform CRUD (Create, Read, Update, Delete) operations with your MongoDB database. This guide will take you through the steps to connect to MongoDB using Mongoose, providing clear examples and explanations along the way.
Before we dive into our Mongoose connection setup, ensure you have the following:
First things first, let's create a new directory for our Node.js application:
mkdir mongoose-crud-app cd mongoose-crud-app
Next, initialize a new npm project:
npm init -y
This command creates a package.json
file in your project directory, setting up your project for dependency management.
We need to install Mongoose as our primary dependency:
npm install mongoose
If you're using TypeScript in your project, you should also install the type definitions for Mongoose:
npm install @types/mongoose --save-dev
Now it’s time to connect our Node.js application to a MongoDB database using Mongoose. Create a new file named app.js
(or app.ts
if you're using TypeScript):
const mongoose = require('mongoose'); // Replace '<URI>' with your MongoDB connection string const uri = '<URI>'; mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Successfully connected to MongoDB'); }) .catch(err => { console.error('Connection error', err); });
You should replace '<URI>'
with your actual connection string. For a local MongoDB instance, it looks like this:
mongodb://localhost:27017/mydatabase
If you're using MongoDB Atlas, you can find your connection string in the Atlas dashboard after setting up your cluster.
With a successful connection, let’s define a simple schema. Below the connection code, add the following:
const Schema = mongoose.Schema; const UserSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true } }); const User = mongoose.model('User', UserSchema);
Now that we have our connection and schema set up, let’s perform some basic CRUD operations. Below the schema definition, add the following code snippets:
const createUser = async () => { const user = new User({ name: 'John Doe', email: 'john.doe@example.com', password: 'securePassword123' }); try { const savedUser = await user.save(); console.log('User Created:', savedUser); } catch (error) { console.error('Error creating user', error); } }; createUser();
const readUsers = async () => { try { const users = await User.find(); console.log('Users:', users); } catch (error) { console.error('Error reading users', error); } }; readUsers();
const updateUser = async (userId) => { try { const updatedUser = await User.findByIdAndUpdate(userId, { name: 'Jane Doe' }, { new: true }); console.log('Updated User:', updatedUser); } catch (error) { console.error('Error updating user', error); } }; // Call updateUser with an existing user ID updateUser('5f50c31b6b58f105b8e29727');
const deleteUser = async (userId) => { try { await User.findByIdAndDelete(userId); console.log('User deleted'); } catch (error) { console.error('Error deleting user', error); } }; // Call deleteUser with an existing user ID deleteUser('5f50c31b6b58f105b8e29727');
In this blog, we've set up a Node.js application, connected to a MongoDB database using Mongoose, and performed basic CRUD operations. As you advance your development skills, Mongoose will continue to be a valuable tool that provides an easy-to-use interface for interacting with MongoDB. Happy coding!
14/10/2024 | NodeJS
31/08/2024 | NodeJS
08/10/2024 | NodeJS
23/07/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
08/10/2024 | NodeJS