This tutorial will guide you on how to use Mongoose for interacting with your MongoDB database. Mongoose is an elegant MongoDB object modeling for Node.js that provides a straightforward, schema-based solution to model your application data.
By the end of this tutorial, you'll learn:
Before using Mongoose, you have to install it via npm.
npm install mongoose
Then, you can import and use it in your Node.js file as shown below:
const mongoose = require('mongoose');
To connect Mongoose to MongoDB, use the mongoose.connect()
function. You'll need to specify your MongoDB URI as one of the parameters.
mongoose.connect('mongodb://localhost/my_database', {useNewUrlParser: true, useUnifiedTopology: true});
The useNewUrlParser
and useUnifiedTopology
options are to handle MongoDB driver deprecation warnings.
A Mongoose model is a blueprint for creating documents within a MongoDB collection. It is defined using the mongoose.model()
function which takes two arguments: the singular name of the collection your model is for and the schema of your model.
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
password: String
});
const User = mongoose.model('User', UserSchema);
To create documents in MongoDB using Mongoose, you can use the save()
method.
const newUser = new User({
name: 'John Doe',
email: 'john@example.com',
password: 'password123'
});
newUser.save((error, document) => {
if (error) console.log(error);
console.log(document);
});
Use the find()
method to read documents from your MongoDB collection.
User.find({name: 'John Doe'}, (error, documents) => {
if (error) console.log(error);
console.log(documents);
});
We have covered how to set up and connect Mongoose to MongoDB, defining a Mongoose model, and performing basic CRUD operations. For further learning, explore Mongoose validation, middleware, and complex queries.
Exercise 1: Create a new Mongoose model for a Product
with name
, price
, and category
fields.
Exercise 2: Write a function to update the price
of a Product
.
Exercise 3: Write a function to delete a Product
from the database.
Solutions:
updateOne()
or updateMany()
functions.deleteOne()
or deleteMany()
functions.Remember, practice makes perfect. Keep trying different operations and exploring the Mongoose documentation for more in-depth knowledge.