Welcome to this MongoDB and Express.js tutorial! Our goal is to set up a MongoDB database and connect it to an Express.js application. This can be achieved using a MongoDB driver or an Object Data Modeling (ODM) tool like Mongoose.
By the end of this tutorial, you will:
Prerequisites:
We will be using Mongoose for this tutorial, an ODM tool that helps in managing relationships between data, provides schema validation, and translates between objects in code and the representation of those objects in MongoDB.
npm install mongoose
First, start your MongoDB server. Then, in your Express.js app, require mongoose and connect to your MongoDB database.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database', {useNewUrlParser: true, useUnifiedTopology: true});
mongodb://localhost/my_database
is the path where your MongoDB server is running.
Schemas are the structure of the document within the collection, they are a powerful way to enforce structure on the data. Models are higher-order constructors that take a schema and create an instance of a document.
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
password: String
});
const User = mongoose.model('User', UserSchema);
You can now use the User model to create, read, update, and delete users in your MongoDB database.
// Create a new user
let user = new User({ name: 'John', email: 'john@example.com', password: '123456' });
user.save();
// Find a user
User.find({name: 'John'}, function(err, users) {
console.log(users);
});
Here's how you create a new user in MongoDB using Mongoose:
let user = new User({ name: 'John', email: 'john@example.com', password: '123456' });
user.save(function (err, user) {
if (err) return console.error(err);
console.log("User saved successfully!");
});
This code creates a new instance of the User model and saves it to the database. If there's an error, it logs that error. Otherwise, it logs a success message.
Here's how you find a user:
User.find({ name: 'John' }, function(err, user) {
if (err) return console.error(err);
console.log(user);
});
This code uses the find method on the User model to find a user with the name 'John'. If there's an error, it logs that error. Otherwise, it logs the user.
In this tutorial, we've learned how to connect a MongoDB database with an Express.js application using Mongoose. We've also learned how to create and find users in MongoDB using Mongoose.
Next steps would include diving deeper into Mongoose and learning about more advanced features such as middleware, validation, and more complex queries.
For further reading, the Mongoose documentation is a great resource!
Create a new user: Create a new user in your MongoDB database with a different name and email than the user we created in the tutorial.
Find a user: Find the user you just created in your MongoDB database.
Update a user: Update the name of the user you just created.
Solutions:
let user = new User({ name: 'Jane', email: 'jane@example.com', password: '654321' });
user.save(function (err, user) {
if (err) return console.error(err);
console.log("User saved successfully!");
});
User.find({ name: 'Jane' }, function(err, user) {
if (err) return console.error(err);
console.log(user);
});
User.updateOne({ name: 'Jane' }, { name: 'Janet' }, function(err, res) {
if (err) return console.error(err);
console.log(res);
});
Keep practicing with different queries and different models to improve your MongoDB and Mongoose skills!