expressjsHow do I connect an Express.js application to a MongoDB database?
Connecting an Express.js application to a MongoDB database is straightforward and can be done in just a few steps.
- Install and configure MongoDB and the Mongoose ORM package:
npm install mongoose
- Create a connection to the MongoDB database:
const mongoose = require('mongoose');
const MONGO_URL = 'mongodb://localhost:27017/myDatabase';
mongoose.connect(MONGO_URL, { useNewUrlParser: true });
- Create a Mongoose schema and model to represent the data in the database:
const userSchema = new mongoose.Schema({
username: String,
email: String
});
const User = mongoose.model('User', userSchema);
- Use the model to perform CRUD operations on the database:
const newUser = new User({
username: 'John Doe',
email: 'jdoe@example.com'
});
newUser.save(function(err) {
if (err) {
console.log(err);
} else {
console.log('User saved successfully!');
}
});
Output example
User saved successfully!
- Finally, use the model in your Express.js routes to interact with the database:
app.get('/users', function(req, res) {
User.find({}, function(err, users) {
if (err) {
res.send(err);
} else {
res.json(users);
}
});
});
These five steps will allow you to connect an Express.js application to a MongoDB database.
Helpful links
More of Expressjs
- How do I set the time zone in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I implement CSRF protection in an Express.js application?
- How do I download a zip file using Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I set up Express.js to listen for requests?
- How can I use Express.js with TypeScript?
- How can I use express-zip js to zip and download files?
- How do I use Yarn to add Express.js to my project?
- How do I use Express.js to read the body of a request?
See more codes...