📅  最后修改于: 2023-12-03 14:40:15.836000             🧑  作者: Mango
MongoDB is a popular NoSQL database, which is widely used by developers to store and retrieve data in JSON-like format. Node.js is a server-side JavaScript runtime, which can be used to create robust and scalable web applications. In this guide, we will learn how to perform CRUD (Create, Read, Update, Delete) operations using MongoDB and Node.js. We will also use GitHub for version control of our code.
To follow along with this guide, you should have:
mkdir mongodb-crud-nodejs-github
cd mongodb-crud-nodejs-github
npm init -y
npm i express mongoose dotenv
.env
file in the root directory of your project and add the following variables:DATABASE_URI = your-mongodb-uri
PORT = 3000
Replace your-mongodb-uri
with the URI of your MongoDB database. You can obtain the URI from your MongoDB Atlas account or from a local MongoDB instance. The PORT
variable is the port number on which your Node.js server will run.
.gitignore
file and add the following entries:node_modules/
.env
This will ensure that we do not commit the node_modules
directory and the .env
file to our GitHub repository.
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/your-github-username/mongodb-crud-nodejs-github.git
git push -u origin master
Let's now create four API endpoints for performing CRUD operations on our MongoDB database.
To create a new document in MongoDB, we need to send a POST request with the document data to the server. The server will then insert the document in the database.
models
directory in the project directory and add a user.js
file with the following contents:const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
});
module.exports = mongoose.model('User', UserSchema);
This file defines a User
model, which will map to a users
collection in the database. Each document in the collection will have a name
, email
, and age
field.
routes
directory in the project directory and add a users.js
file with the following contents:const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.post('/', async (req, res) => {
const { name, email, age } = req.body;
const newUser = new User({ name, email, age });
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
module.exports = router;
This file defines a POST /
endpoint for creating a new user. It receives the user data from the request body, creates a new User
object, and saves it to the database. If the operation is successful, it returns the newly created user with a status code of 201 (Created), otherwise it returns an error message with a status code of 400 (Bad Request).
app.js
file to register the users
route:const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const usersRouter = require('./routes/users');
dotenv.config();
const app = express();
mongoose.connect(process.env.DATABASE_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', (err) => console.error(err));
db.once('open', () => console.log('Connected to database'));
app.use(express.json());
app.use('/users', usersRouter);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server listening on port ${port}`));
This file connects to the MongoDB database using the DATABASE_URI
variable, registers the users
route, and starts the server.
npm start
POST /users
endpoint using a tool like Postman or cURL. Send a JSON payload with the user data:{
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}
You should receive a response with the newly created user object.
To retrieve documents from MongoDB, we can use various queries based on the requirements. Here, we will create a GET /users
endpoint to retrieve all the users in the database.
users.js
file to add the GET /
endpoint:router.get('/', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
This code retrieves all the users from the users
collection and returns them as a JSON array. In case of an error, it returns a 500 (Internal Server Error) status code with an error message.
GET /users
endpoint using a tool like Postman or cURL. You should receive a response with all the users in the database.To update an existing document in MongoDB, we can use the updateOne
method of the User
model. Here, we will create a PATCH /users/:id
endpoint to update a user based on their ID.
users.js
file to add the PATCH /:id
endpoint:router.patch('/:id', async (req, res) => {
const { name, email, age } = req.body;
try {
const updatedUser = await User.updateOne(
{ _id: req.params.id },
{ $set: { name, email, age } }
);
res.json(updatedUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
This code receives the updated data from the request body and uses the updateOne
method to update the user with the given ID. If the operation is successful, it returns the updated user, otherwise it returns an error message.
PATCH /users/:id
endpoint using a tool like Postman or cURL. Send a JSON payload with the updated user data:{
"name": "Jane Doe",
"email": "jane.doe@example.com",
"age": 35
}
Replace :id
in the endpoint URL with the ID of an existing user.
You should receive a response with the updated user object.
To remove a document from MongoDB, we can use the deleteOne
method of the User
model. Here, we will create a DELETE /users/:id
endpoint to delete a user based on their ID.
users.js
file to add the DELETE /:id
endpoint:router.delete('/:id', async (req, res) => {
try {
const deletedUser = await User.deleteOne({ _id: req.params.id });
res.json(deletedUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
This code uses the deleteOne
method to remove the user with the given ID. If the operation is successful, it returns the deletion status object, otherwise it returns an error message.
DELETE /users/:id
endpoint using a tool like Postman or cURL. Replace :id
in the endpoint URL with the ID of an existing user. You should receive a response with the deletion status object.In this guide, we learned how to perform CRUD operations using MongoDB and Node.js. We also used GitHub for version control of our code. You can extend this project further by adding more features and APIs, applying validation and authentication, and deploying the application to a production environment.