返回
构建你自己的 Express+MongoDB 后端应用——教程
前端
2023-11-27 23:58:30
在过去的十年里,Node.js 一直是开发人员构建后端应用程序的首选,它的受欢迎程度一直在不断上升。而今天,我们将使用 Express.js 和 MongoDB,这两个 Node.js 的流行框架,从头开始创建一个后端应用程序。
Express.js 是一个轻量级框架,用于构建 Web 应用程序和 API,而 MongoDB 是一个文档数据库,可以轻松存储和检索数据。
开始
安装必要的软件包:
npm install express mongodb
创建 Express.js 应用程序
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
连接到 MongoDB
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient('mongodb://localhost:27017', {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.connect(err => {
if (err) throw err;
const db = client.db('my-database');
const collection = db.collection('my-collection');
// Insert a document
collection.insertOne({ name: 'John Doe', age: 30 }, (err, result) => {
if (err) throw err;
console.log(`A document was inserted with the _id: ${result.insertedId}`);
});
// Find a document
collection.findOne({ name: 'John Doe' }, (err, result) => {
if (err) throw err;
console.log(result);
});
// Update a document
collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } }, (err, result) => {
if (err) throw err;
console.log(`The document with the _id: ${result.matchedCount} was updated.`);
});
// Delete a document
collection.deleteOne({ name: 'John Doe' }, (err, result) => {
if (err) throw err;
console.log(`The document with the _id: ${result.deletedCount} was deleted.`);
});
// Close the connection
client.close();
});
运行应用程序
node index.js
结论
在本教程中,我们学习了如何使用 Express.js 和 MongoDB 从头开始创建一个后端应用程序。我们还学习了如何连接到 MongoDB 并执行基本的数据库操作。