来源:https://www.mongodb.com/zh-cn/compatibility/express
Express.js (or simply Express) is a web application server framework for Node.js, and MongoDB is a general-purpose document database platform. Expressjs(或简称Express)是一个用于Node.js的web应用服务器框架,MongoDB是一个通用文档数据库平台。You can use these together to build a web application that stores data in MongoDB. 您可以将这些功能结合起来,构建一个在MongoDB中存储数据的web应用程序。Since Express is a module running on top of Node.js, you can use the MongoDB Node.js driver to connect to any MongoDB database instance and query it.由于Express是运行在Node.js之上的模块,因此可以使用MongoDB Node.js驱动程序连接到任何MongoDB数据库实例并进行查询。
Express is a minimal web application framework for Node.js. Express是Node.js的最小web应用程序框架。It is designed to be fast, minimal, and modular. 它被设计为快速、最小和模块化。Express is a free and open-source MIT-licensed project. Express是麻省理工学院授权的免费开源项目。It is part of the OpenJS foundation and has an active community of contributors.它是OpenJS基金会的一部分,并且有一个积极的贡献者社区。
Express extends the Node.js Express使用路由、中间件和视图等功能扩展了Node.js http
package with features for routing, middlewares, and views. http
包。Express is often used for creating APIs, especially REST APIs. Express通常用于创建API,尤其是REST API。The following sample implements a REST-like API with Express in only 20 lines of code!下面的示例仅用20行代码就用Express实现了一个类似REST的API!
const express = require('express');
const app = express();
app.get('/products', (req, res) => {
return res.send('GET HTTP method on product resource');
});
app.post('/products', (req, res) => {
return res.send('POST HTTP method on product resource');
});
app.put('/products/:productId', (req, res) => {
return res.send(`PUT HTTP method on product/${req.params.productId} resource`);
});
app.delete('/products/:productId', (req, res) => {
return res.send(`DELETE HTTP method on product/${req.params.productId} resource`);
});
app.listen(3000, () => console.log('Server is running on port 3000'));
The code above uses methods of the 上面的代码使用app
object that correspond to HTTP methods—GET, POST, PUT, and DELETE. app
对象的方法,这些方法对应于HTTP方法GET
、POST
、PUT
和DELETE
。For example, the 例如,app.get()
method is used to handle a GET request on the /products
route. app.get()
方法用于处理/products
路由上的GET请求。Similarly, the 类似地,app.put()
method is used to handle a PUT request on the /products/:productId
route, where :productId
is a parameter that is extracted from the URL.app.put()
方法用于处理/products/:productId
路由上的PUT请求,其中:productId
是从URL提取的参数。
You can build on top of this simple routing example to work with real data. 您可以在这个简单的路由示例的基础上使用真实数据。A common use case is to create a REST API that stores data in a database, such as MongoDB. 一个常见的用例是创建一个REST API,将数据存储在数据库中,比如MongoDB。The different resources exposed as endpoints from the API represent collections in the database. API中作为端点公开的不同资源代表数据库中的集合。For example, the 例如,/products
endpoint represents the collection of products stored in the database./products
端点表示存储在数据库中的产品集合。
For a full tutorial on how to build a REST API with Express and MongoDB, see Building a REST API with Express, Node, and MongoDB.有关如何使用Express和MongoDB构建REST API的完整教程,请参阅使用Express、Node和MongoDB构建REST API。
You can use MongoDB in your Express application by installing the MongoDB Node.js driver. 通过安装MongoDB Node.js驱动程序,可以在Express应用程序中使用MongoDB。The MongoDB Node.js driver is a Node.js module that allows you to connect your application to MongoDB and work with your data.MongoDB Node.js驱动程序是一个Node.js模块,允许您将应用程序连接到MongoDB并处理数据。
If you're building a REST API, it's considered a good practice to split your routing logic from your data storage logic. 如果您正在构建一个REST API,那么将路由逻辑与数据存储逻辑分离被认为是一种良好的做法。For example, you might have a Product controller that handles requests for the 例如,您可能有一个处理/products
resource, and a Product
model that stores the data. /products
资源请求的产品控制器,以及一个存储数据的Product
模型。There are a number of popular JavaScript frameworks based on Express that do this for you. 有许多基于Express的流行JavaScript框架可以为您实现这一点。Let's take a look at some of them.让我们来看看其中的一些。
Express is a robust solution that has been around for more than 10 years. Express是一款稳健的解决方案,已有10多年的历史。It is a great choice for building APIs, especially REST APIs. 对于构建API,尤其是REST API,它是一个很好的选择。However, the JavaScript ecosystem is constantly evolving. 然而,JavaScript生态系统在不断发展。Following Express, many JavaScript frameworks have been created to provide a more comprehensive and powerful set of features. 继Express之后,创建了许多JavaScript框架,以提供更全面、更强大的功能集。Some of these frameworks, such as NestJS, integrate Express to expose similar routing and middleware capabilities. 其中一些框架(如NestJS)集成了Express,以公开类似的路由和中间件功能。Others, such as Koa and Fastify, are considered to be only “inspired” by Express, providing more performant and developer-friendly solutions than the latter. 其他的,如Koa和Fastify,被认为是“灵感”的Express,提供更多的性能和开发人员友好的解决方案比后者。Let's take a closer look at each of these frameworks.让我们仔细看看每一个框架。
Koa is a lightweight Node.js framework. Koa是一种轻量级的Node.js框架。It is built by the original team behind Express. 它是由Express背后的原始团队建造的。The main difference between Koa and Express is the way both frameworks implement middleware. Koa和Express之间的主要区别是两种框架都实现中间件的方式。Koa doesn't have a built-in middleware mechanism but relies on promises and async functions for controlling the program flow. Koa没有内置的中间件机制,但依赖于控制程序流的承诺和异步功能。This allows you to stop relying on callbacks and thus, helps you escape the so-called “callback hell.” 这让你不再依赖回调,从而帮助你逃离所谓的“回调地狱”
Another difference is that Koa doesn't provide routing out of the box. 另一个不同之处在于Koa没有提供路由选择。Instead, you can use third-party Node modules such as 相反,您可以使用第三方节点模块(如koa-router
or koa-route
to implement routing.koa-router
或koa-route
)来实现路由。
Fastify is a general-purpose server framework for Node that shines with its highly-optimized HTTP APIs. Fastify是一个针对Node的通用服务器框架,其高度优化的HTTP API非常出色。The framework aims to be as fast as possible and the benchmarks comparing it to other Node frameworks back up that claim.该框架的目标是尽可能快,将其与其他节点框架进行比较的benchmarks支持这一说法。
Additionally, Fastify provides an extensible plugin architecture and a growing ecosystem of plugins. 此外,Fastify还提供了一个可扩展的插件体系结构和一个不断增长的插件生态系统。The architecture is designed to ensure plugin independence and encapsulation. 该架构旨在确保插件独立性和封装性。This eliminates a myriad of issues caused by cross dependencies and allows you to refactor your code without worrying about breaking other parts of the application.这消除了由交叉依赖性引起的大量问题,并允许您重构代码,而无需担心破坏应用程序的其他部分。
NestJS (sometimes referred to as Nest) is a framework that provides an additional level of abstraction above frameworks like Express and Fastify. NestJS(有时被称为Nest)是一个框架,它在Express和Fastify等框架之上提供了额外的抽象级别。It comes with an out-of-the-box application architecture that helps you iterate and scale fast. 它附带了一个现成的应用程序体系结构,可以帮助您快速迭代和扩展。The architecture of NestJS is heavily inspired by Angular. NestJS的架构深受Angular的启发。Similar to Angular, NestJS is built from the ground up with TypeScript and NestJS applications are written in TypeScript.与Angular类似,NestJS是用TypeScript从头开始构建的,NestJS应用程序是用TypeScript编写的。
NestJS uses Express for providing HTTP capabilities. NestJS使用Express提供HTTP功能。However, it's easy to replace Express with another framework such Fastify, taking advantage of the better performance of the latter.然而,很容易用另一个框架(如Fastify)替换Express,从而利用后者更好的性能。
As mentioned above, NestJS comes with a lot of built-in architecture solutions, including a solution for database communication. 如上所述,NestJS提供了许多内置的体系结构解决方案,包括数据库通信解决方案。NestJS provides integration with Sequelize and TypeORM, which can be used to connect to a SQL or non-relational database, such as MongoDB. NestJS提供了与Sequelize和TypeORM的集成,可用于连接SQL或非关系数据库,如MongoDB。There's also a Mongoose integration supported by the NestJS team. NestJS团队还支持Mongoose集成。However, NestJS is flexible enough and you can also connect to your database by loading its native Node.js driver.不过,NestJS足够灵活,您还可以通过加载其本机Node.js驱动程序连接到数据库。
Express is the most widely used Node.js framework. Express是应用最广泛的Node.js框架。It has a strong community of contributors and is used by a wide variety of real-world projects. 它有一个强大的贡献者社区,被各种各样的现实项目使用。It is also a great choice for building APIs that has proven itself over time.对于构建经过长期验证的API来说,它也是一个不错的选择。
Express is an unopinionated framework that is easy to learn and use. Express是一个易于学习和使用的非专用框架。You can extend it as you like and you can use it together with any other Node.js module or library.您可以根据需要扩展它,并且可以将其与任何其他Node.js模块或库一起使用。
Express is one of the most widely used JavaScript frameworks. Express是使用最广泛的JavaScript框架之一。It has an enormous community which means you'll easily find answers to your questions when building with Express.它有一个庞大的社区,这意味着在使用Express构建时,您可以轻松找到问题的答案。
MEAN (MongoDB, Express, Angular, and Node.js) and MERN (MongoDB, Express, React, and Node.js) are popular JavaScript tech stacks for building end-to-end web applications. MEAN(MongoDB、Express、Angular和Node.js)和MERN(MongoDB、Express、React和Node.js)是构建端到端web应用程序的流行JavaScript技术栈。Express is one of the four essential technologies that form the MEAN and MERN stacks. Express是构成MEAN和MERN堆栈的四项基本技术之一。The other three are:其他三项是:
When building MEAN/MERN applications, Express is used for building the REST API. 在构建MEAN/MERN应用程序时,Express用于构建REST API。This API is used for communication between the client-side application and the server-side application. 此API用于客户端应用程序和服务器端应用程序之间的通信。
If you want to learn more about the MEAN and MERN stacks, you can read the dedicated MEAN and MERN articles.如果你想了解更多关于MEAN和MERN堆栈的信息,你可以阅读专门的MEAN和MERN文章。
Express is a great choice for building REST APIs. Express是构建REST API的最佳选择。Because Express runs on top of Node.js, you can easily connect to a MongoDB instance using the MongoDB Node.js driver. 因为Express运行在Node.js之上,所以可以使用MongoDB Node.js驱动程序轻松连接到MongoDB实例。If you want to learn more, follow this full-blown tutorial for Building a REST API with Express, Node, and MongoDB.如果您想了解更多信息,请遵循本完整教程《使用Express、Node和MongoDB构建REST API》。
You can connect to any MongoDB database instance with the MongoDB Node.js driver. 您可以使用MongoDB Node.js驱动程序连接到任何MongoDB数据库实例。Since Express is running on Node.js, you can use the driver with Express as well.由于Express在Node.js上运行,因此您也可以将驱动程序与Express一起使用。
Express doesn't have a built-in concept for a database. Express没有数据库的内置概念。You can use any database driver that is compatible with Node.js. 您可以使用任何与Node.js兼容的数据库驱动程序。For example, you can connect to MongoDB with the MongoDB Node.js driver.例如,您可以使用MongoDB Node.js驱动程序连接到MongoDB。
Node.js (or Node) is a JavaScript runtime environment. Node.js(或Node)是一个JavaScript运行时环境。Express is a JavaScript framework that is built on top of Node.js and provides additional capabilities for building APIs and web applications.Express是一个JavaScript框架,构建在Node.js之上,为构建API和web应用程序提供了额外的功能。
You can use the Express routing mechanism to register routes that correspond to HTTP methods—GET, POST, PUT, and DELETE. 您可以使用Express路由机制注册与HTTP方法GET、POST、PUT和DELETE相对应的路由。Through these routes, you can perform CRUD (Create, Read, Update, and Delete) operations on collections in your MongoDB database. 通过这些路由,您可以对MongoDB数据库中的集合执行CRUD(创建、读取、更新和删除)操作。For a full tutorial, check out the Building a REST API with Express, Node, and MongoDB. 有关完整教程,请查看《使用Express、Node和MongoDB构建REST API》。
Follow along with this tutorial to add MongoDB Atlas as the data store for your applications, by creating NodeJS and Express Web REST API.遵循本教程,通过创建NodeJS和expresswebrestapi,将MongoDB Atlas添加为应用程序的数据存储。
JavaScript is considered the top web development language today, running in millions of applications and websites. JavaScript被认为是当今顶级的web开发语言,在数百万个应用程序和网站上运行。One of the building blocks for the JavaScript stack, on many of its variations, is REST API-based communication between the front-end and back-end tiers.JavaScript堆栈的许多变体的一个构建块是前端和后端层之间基于REST API的通信。
A popular way of implementing the REST API approach uses Express JS as the back-end web server and MongoDB as the document store. 实现REST API方法的一种流行方式是使用Express JS作为后端web服务器,使用MongoDB作为文档存储。This concept easily maps MongoDB’s document model to the REST API payloads which are JSON by nature.这个概念很容易将MongoDB的文档模型映射到本质上是JSON的REST API有效负载。
This article will provide a step-by-step tutorial on how to use Express with MongoDB Atlas, our Database-as-a-Service platform, to expose restful API endpoints for our clients.本文将提供一个分步教程,介绍如何将Express与数据库即服务平台MongoDB Atlas结合使用,为客户公开restful API端点。
Table of Contents目录
You can explore the full project in the following GitHub repo:您可以在以下GitHub repo中浏览整个项目:
Express allows us to create a back-end middle tier running Node.js server exposing REST API routes to our application. Express允许我们创建一个后端中间层,运行Node.js服务器,向应用程序公开REST API路由。
The Express.js server also connects to the MongoDB Atlas cluster via the Node.js Driver. Expressjs服务器还通过Node.js驱动程序连接到MongoDB Atlas集群。If you wish to learn more about MongoDB and Node.js, read the following article. 如果您想了解更多关于MongoDB和Node.js的信息,请阅读以下文章。
Finally, our front-end application will be written in React to use the REST API endpoints hosted on the Express.js server. 最后,前端应用程序将用React编写,以使用托管在Expressjs服务器上的REST API端点。The application is a Tinder-like application for the sample_airbnb database, containing information on various listings, available as part of the sample datasets you can load into the Atlas cluster. 该应用程序是sample_airbnb数据库的一个类似Tinder的应用程序,包含各种列表的信息,可以作为示例数据集的一部分加载到Atlas集群中。
Users can swipe the listing cards to save or drop them and press the “like” button to add likes. 用户可以滑动列表卡保存或删除它们,然后按“喜欢”按钮添加喜欢的内容。Additionally, a double click will show details about the specific listing card presented.此外,双击将显示所显示的特定挂牌卡的详细信息。
Here are the main files in the project:以下是项目中的主要文件:
The “server” directory hosts the Express.js server application and all of its dependencies. server
目录承载Express.js服务器应用程序及其所有依赖项。The main files here are:这里的主要文件是:
The “app/listings” directory is where the front-end React application code resides. app/listings
目录是前端React应用程序代码所在的目录。The main files here are:这里的主要文件是:
First, you will need to deploy an Atlas cluster. 首先,您需要部署一个Atlas集群。You can follow the Getting Started with Atlas guide to learn how to create a free Atlas account, create your first cluster, and get your connection string to the database. 您可以按照《Atlas入门指南》学习如何创建免费Atlas帐户、创建第一个集群,以及获取到数据库的连接字符串。
Once we have the Atlas cluster available, we can load the sample data by clicking [...] > “Load Sample Data.” 一旦Atlas集群可用,我们可以通过单击[…]>“加载样本数据”来加载样板数据。When data is loaded, we are ready to clone the project stub branch:加载数据后,我们准备克隆项目存根分支:
git clone -b stub
git@github.com:mongodb-developer/mongodb-express-rest-api-example.git
Let’s go to the “server” directory of the project and install the needed packages:让我们转到项目的“服务器”目录,安装所需的软件包:
cd mongodb-express-rest-api-example/server
npm install
Now, we are ready to connect our Express server to the MongoDB Atlas Cluster.现在,我们已经准备好将Express服务器连接到MongoDB Atlas集群。
Once you locate your connection string, create a config.env file in the server directory. 找到连接字符串后,在服务器目录中创建一个config.env文件。There, assign a new ATLAS_URI variable the value of the connection string. 在这里,为连接字符串的值分配一个新的ATLAS_URI变量。Replace the 用数据库用户名和密码替换<username>
and the <password>
with your database username and password. <username>
和<password>
。Once done, your file should look similar to the one below.完成后,您的文件应该与下面的文件类似。
ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
Next, open server/db/conn.js and add the implementation of the connectToServer function from the snippet below.接下来,打开server/db/conn.js,从下面的代码片段中添加connectToServer
函数的实现。
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db("sample_airbnb");
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
The main object this module exports out is the 该模块导出的主要对象是_db
variable, which will hold the "sample_airbnb
" database-level object. _db
变量,它将保存“sample_airbnb
”数据库级对象。Via this object, we will be able to access any collection within that database or change its context to another database. 通过这个对象,我们将能够访问该数据库中的任何集合,或者将其上下文更改为另一个数据库。In this tutorial, we will use only a single database named “在本教程中,我们将只使用一个名为“sample_airbnb
.”sample_airbnb
”的数据库
The main Express.js part in this tutorial is to expose REST API routes to perform Read, Create, Update, and Delete operations for our listing application. 本教程中Expressjs的主要部分是公开REST API路由,以便为列表应用程序执行读取、创建、更新和删除操作。This can be extended for more complex application business logic as your use case requires.这可以根据您的用例需要扩展为更复杂的应用程序业务逻辑。
The file that will host the routes is --- “server/routes/record.js”. 将承载路由的文件是--“server/routes/record.js”。It uses the Express Router feature:它使用Express路由器功能:
const express = require("express");
// recordRoutes is an instance of the express router.recordRoutes是express router的一个实例。
// We use it to define our routes.我们用它来定义路由。
// The router will be added as a middleware and will take control of requests starting with path /listings.路由器将作为中间件添加,并将控制从路径/列表开始的请求。
const recordRoutes = express.Router();
The Read route will be used when the 当调用GET方法上的/listings
path on a GET method is called. /listings
路径时,将使用读取路由。It will use a collection.find() to query our 它将使用listingAndReviews
collection for the first 50 available listings:collection.find()
来查询listingAndReviews
集合中的前50个可用列表:
// This section will help you get a list of all the documents.本节将帮助您获得所有文档的列表。
recordRoutes.route("/listings").get(async function (req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("listingsAndReviews")
.find({}).limit(50)
.toArray(function (err, result) {
if (err) {
res.status(400).send("Error fetching listings!");
} else {
res.json(result);
}
});
});
The code sends back the result set as the API response.代码将结果集作为API响应发回。
The Create route will record a “match” swipe in a “matches” collection. 创建路由将在“匹配”集合中记录“匹配”滑动。The body of this POST method will present a user 此POST方法的主体将显示一个用户session_id
and the swiped direction and listing_id
to create a “match” document.session_id
以及滑动方向和listing_id
,以创建一个“匹配”文档。
// This section will help you create a new document.本节将帮助您创建新文档。
recordRoutes.route("/listings/recordSwipe").post(function (req, res) {
const dbConnect = dbo.getDb();
const matchDocument = {
listing_id: req.body.id,
last_modified: new Date(),
session_id: req.body.session_id,
direction: req.body.direction
};
dbConnect
.collection("matches")
.insertOne(matchDocument, function (err, result) {
if (err) {
res.status(400).send("Error inserting matches!");
} else {
console.log(`Added a new match with id ${result.insertedId}`);
res.status(204).send();
}
});
});
The save is done via collection.insertOne() method with the prebuilt “matchDocument.”通过collection.insertOne()
方法和预构建的“matchDocument”完成保存
You can also use InsertMany to insert multiple documents at once. 还可以使用InsertMany
一次插入多个文档。
The Update route updates the “likes” field on a listing object. 更新路由更新列表对象上的“likes”字段。This is done via a POST method:这是通过POST方法完成的:
// This section will help you update a document by id.本节将帮助您按id更新文档。
recordRoutes.route("/listings/updateLike").post(function (req, res) {
const dbConnect = dbo.getDb();
const listingQuery = { _id: req.body.id };
const updates = {
$inc: {
likes: 1
}
};
dbConnect
.collection("listingsAndReviews")
.updateOne(listingQuery, updates, function (err, _result) {
if (err) {
res.status(400).send(`Error updating likes on listing with id ${listingQuery.id}!`);
} else {
console.log("1 document updated");
}
});
});
The method will use the collection.updateOne() method with a $inc on the “like” field to increment the likes.该方法将使用collection.updateOne()
方法,在“like”字段上加一个$inc
来增加like。
Whenever a listing is dropped, we can delete it from the database so that it doesn’t appear anymore. 无论何时删除列表,我们都可以将其从数据库中删除,使其不再出现。This is done via the Delete route. 这是通过删除路由完成的。
// This section will help you delete a record.本节将帮助您删除记录。
recordRoutes.route("/listings/delete/:id").delete((req, res) => {
const dbConnect = dbo.getDb();
const listingQuery = { listing_id: req.body.id };
dbConnect
.collection("listingsAndReviews")
.deleteOne(listingQuery, function (err, _result) {
if (err) {
res.status(400).send(`Error deleting listing with id ${listingQuery.listing_id}!`);
} else {
console.log("1 document deleted");
}
});
});
The route here includes the 此处的路由包括:id
parameter. :id
参数。This is the id of the listing to be deleted via collection.deleteOne().这是要通过collection.deleteOne()
删除的列表的id。
Now that we have everything in place, we can launch the server:现在一切就绪,我们可以启动服务器:
npm start
[nodemon] starting `node server.js`
Successfully connected to MongoDB.
Server is running on port: 5000
Our React application consists mainly of the App.js React file and class.React应用程序主要由Appjs React文件和类组成。
import './App.css';
import TinderCard from 'react-tinder-card'
import axios from 'axios';
import { Component } from 'react';
import { v4 as uuid } from 'uuid';
class App extends Component {
constructor() {
super();
this.state = {
data: [],
session_id: uuid(),
liked: false
};
this.handleClick = this.handleClick.bind(this);
this.showDetails = this.showDetails.bind(this);
}
async onSwipe(direction, listingId, sessionId) {
this.setState({
liked: false
});
if (direction === "left") {
await axios.delete(`http://localhost:5000/listings/delete/${listingId}`)
} else {
await axios.post("http://localhost:5000/listings/recordSwipe", { id: listingId, session_id: sessionId, direction })
}
}
async handleClick(listingId) {
this.setState({
liked: !this.state.liked
});
await axios.post("http://localhost:5000/listings/updateLike", { id: listingId });
}
showDetails(listing) {
alert(`Name: ${listing.name}\n Price : $${listing.price['$numberDecimal']} \n Minimum Nights : ${listing.minimum_nights}\n Beds : ${listing.beds}`);
}
async componentWillMount() {
const response = await axios.get(`http://localhost:5000/listings`);
const json = await response.data;
this.setState({ data: json });
}
render() {
const likeButtonLabel = this.state.liked ? '❤' : 'Like';
return (
<div className="app">
<div>
<h1>LisTinder</h1>
<h2>Swipe left for drop or right to save...</h2>
<div className="card-container">
{this.state.data.map((listing) =>
<TinderCard className='swipe' key={listing.name} onSwipe={(dir) => this.onSwipe(dir, listing._id)} >
<div style={{ backgroundImage: 'url(' + listing.images.picture_url + ')' }} className='card'>
<div className="card-details">
<h3>{listing.name}</h3>
<div className="card-actions">
<button className="button" onClick={() => this.handleClick(listing._id)}>{likeButtonLabel}</button>
<button className="button" onClick={() => this.showDetails(listing)}>See Details</button>
</div>
</div>
</div>
</TinderCard>
)}
</div>
</div>
</div>
);
}
}
export default App;
We will use some third-party modules, like the “react-tinder-card”, which will allow us to create the swiping tiles and graphics. 我们将使用一些第三方模块,比如“react-tinder-card”,它将允许我们创建刷卡和图形。Those will interact with the application functions to handle events like “onSwipe,” “handleLikeClick,” “showDetails,” and “componentWillMount” (to show the data on page load).它们将与应用程序函数交互,以处理诸如“onswip”、“handleLikeClick”、“showDetails”和“componentWillMount”(在页面加载时显示数据)之类的事件。
Functions “onSwipe,” “handleLikeClick,” and “componentWillMount” will use the axios library to perform http REST API requests to our Express server. 函数“onSwipe”、“handleLikeClick”和“componentWillMount”将使用axios库对Express服务器执行http REST API请求。Those, in turn, will perform the needed action on our Atlas cluster.反过来,它们将在Atlas集群上执行所需的操作。
Now we can start the application in a new terminal (the server process must remain running):现在,我们可以在新的终端中启动应用程序(服务器进程必须保持运行):
cd ../app/listings
npm install
npm start
Once all components are up and running, we can open the http://localhost:3000 URL and we should see our “LisTinder” application loaded:一旦所有组件都启动并运行,我们就可以打开http://localhost:3000我们应该看到“LisTinder”应用程序已加载:
Main App | Swipe Cards | Show Details |
---|---|---|
![]() | ![]() | ![]() |
Interaction with the tiles by swapping them will call our Express routes and perform application operations.通过交换磁片与磁片进行交互,将调用快速路由并执行应用程序操作。
Successfully connected to MongoDB.
1 document updated
1 document deleted
MongoDB Realm, MongoDB’s mobile database and development cloud services, offer a robust and scalable replacement to the self-hosted Express Server. ,MongoDB的移动数据库和开发云服务,为自托管的Express服务器提供了一个强大且可扩展的替代品。
Creating an application is very easy with a generous free tier. 创建一个应用程序非常容易,有一个慷慨的免费层。In that application, you can create HTTP services with webhook endpoints to perform the same operations as the Express routes, without the need for maintaining and coding lots of boilerplate code. 在该应用程序中,您可以使用webhook端点创建HTTP服务,以执行与Express routes相同的操作,而无需维护和编写大量样板代码。Those services are optimised for Atlas cluster access and will open a new world of opportunities like cloud functions, auth providers, GraphQL, and triggers.这些服务针对Atlas群集访问进行了优化,并将打开一个新的机会世界,如云功能、身份验证提供商、GraphQL和触发器。
Let’s port one route to a webhook. We will start by creating an HTTP service within a newly created Realm application UI.让我们将一条路径移植到webhook。我们将首先在新创建的领域应用程序UI中创建一个HTTP服务。
Navigate to the “3d Party Services” section and click on the HTTP service type. 导航到“3d Party Services”部分并单击HTTP服务类型。
As part of defining the service, we need to configure the HTTP method this webhook will use and its associated function logic.作为定义服务的一部分,我们需要配置此webhook将使用的HTTP方法及其关联的功能逻辑。
The associated function code:关联的功能代码:
// This function is the webhook's request handler.
exports = async function(payload, response) {
// Querying a mongodb service:
return await context.services.get("mongodb-atlas").db("sample_airbnb").collection("listingsAndReviews").find({}).limit(50);
};
Now we can use the webhook URL directly in the React application. 现在我们可以在React应用程序中直接使用webhook URL。Add the following to the app class in App.js:将以下内容添加到Appjs中的app类:
async componentWillMount() {
const response = await axios.get(`<PASTE-YOUR-WEBHOOK-URL>`);
const json = await response.data;
this.setState({ data: json });
}
Wow, that's much easier and more scalable!哇,这更简单,更具可扩展性!
Using Express as a back-end middleware is a popular MongoDB stack design. 使用Express作为后端中间件是流行的MongoDB堆栈设计。Express is lightweight and approachable for JSON and REST API operations. Express对于JSON和restapi操作来说是轻量级的、可接近的。MongoDB Atlas is a scalable and flexible document Database-as-a-Service and makes a perfect companion to Express in many stacks like MERN, MEAN, and MEVN.MongoDB Atlas是一个可扩展且灵活的文档数据库即服务,是在MERN、MEAN和MEVN等多个堆栈中表达的完美伴侣。
Having said that, MongoDB Realm Development Services and webhooks are a robust replacement for the Express tier, moving the need to manage an Express server and its dependencies on-prem.话虽如此,MongoDB Realm Development Services和webhooks是Express层的强大替代品,从而消除了对Express服务器及其依赖关系的管理需求。
The MongoDB Driver is the native driver for Node JS applications. MongoDB驱动程序是Node JS应用程序的本机驱动程序。Therefore, the Express JS server can use it to access MongoDB.因此,Express JS服务器可以使用它访问MongoDB。
In this article, we covered the essential parts of setting up an Express server with connection to MongoDB Atlas as well as exposing REST API endpoints to the client applications.在本文中,我们介绍了设置连接到MongoDB Atlas的Express服务器以及向客户机应用程序公开REST API端点的基本部分。
Visit the following links:请访问以下链接: