by Zell Liew

由Zell Liew

使用Express和MongoDB构建简单的CRUD应用程序 (Building a Simple CRUD Application with Express and MongoDB)

For a long time, I didn’t dare venture into back end development. I felt intimidated because of my lack of an academic background in programming.

很长一段时间,我都不敢冒险进行后端开发。 由于缺乏编程方面的学术背景,我感到胆怯。

I remember when I eventually built up the courage to try back end development. I had such a hard time understanding the documentation for Express, MongoDB, and Node.js that I gave up.

我记得当我最终鼓起勇气尝试后端开发时。 我很难理解我放弃的Express,MongoDB和Node.js的文档。

I eventually went back and worked through my confusion. Now, one year later, I understood how to work with these tools. So, I decided to write this comprehensive tutorial so you won’t have to go through the same headache that I went through.

我最终回过头来,度过了困惑。 一年后的现在,我了解了如何使用这些工具。 因此,我决定编写此综合教程,这样您就不必再经历与我经历的同样的头痛了。

CRUD,Express和MongoDB (CRUD, Express and MongoDB)

CRUD, Express and MongoDB are big words for a person who has never touched any server-side programming in their life. Let’s quickly introduce what they are before we diving into the tutorial.

对于一个从未接触过任何服务器端编程的人来说,CRUD,Express和MongoDB是个好话。 在深入学习本教程之前,让我们快速介绍一下它们是什么。

Express is a framework for building web applications on top of Node.js. It simplifies the server creation process that is already available in Node. In case you were wondering, Node allows you to use JavaScript as your server-side language.

Express是一个用于在Node.js之上构建Web应用程序的框架。 它简化了Node中已经可用的服务器创建过程。 如果您想知道,Node允许您将JavaScript用作服务器端语言。

MongoDB is a database. This is the place where you store information for your web websites (or applications).

MongoDB是一个数据库。 这是您存储网站(或应用程序)信息的地方。

CRUD is an acronym for Create, Read, Update and Delete. It is a set of operations we get servers to execute (POST, GET, PUT and DELETE respectively). This is what each operation does:

CRUD是创建,读取,更新和删除的首字母缩写。 这是我们让服务器执行的一组操作(分别是POST,GET,PUT和DELETE)。 这是每个操作的作用:

  • Create (POST) — Make something

    创建(POST) -做点什么

  • Read (GET)_- Get something

    读(GET) _-得到一些东西

  • Update (PUT) — Change something

    更新(PUT) -更改某些内容

  • Delete (DELETE)– Remove something

    删除(删除) –删除某些内容

If we put CRUD, Express and MongoDB together into a single diagram, this is what it would look like:

如果将CRUD,Express和MongoDB放到一个图表中,它将是这样的:

Does CRUD, Express and MongoDB makes more sense to you now?

CRUD,Express和MongoDB现在对您有意义吗?

Great. Let’s move on.

大。 让我们继续。

我们正在建立的 (What we’re building)

We’re going to build an application simple list application that allows you to keep track of things within a list (like a Todo List for example).

我们将构建一个简单的应用程序列表应用程序,使您可以跟踪列表中的内容(例如Todo List)。

Well, a todo list is kind of boring. How about we make a list of quotes from Star wars characters instead? Awesome, isn’t it? Feel free to take a quick look at the demo before continuing with the tutorial. Also, this is where you can find the finished code for the application.

好吧,待办事项清单有点无聊。 我们如何列出《星球大战》角色的报价单呢? 太好了,不是吗? 在继续学习本教程之前,请随时快速浏览一下该演示 。 另外, 在这里您可以找到应用程序的完成代码。

By the way, what we’re building isn’t a sexy single page app. We’re mainly focusing on how to use CRUD, Express and Mongo DB in this tutorial, so, more server-side stuff. I’m not going to emphasize style.

顺便说一句,我们正在构建的并不是一个性感的单页应用程序。 在本教程中,我们主要侧重于如何使用CRUD,Express和Mongo DB,因此,还有更多服务器端内容。 我不会强调风格。

You’ll need two things to get started with this tutorial:

您将需要两件事来开始本教程:

  1. You shouldn’t be afraid of typing commands into a shell. Check out this article if you currently are.

    您不必担心在shell中键入命令。 如果您当前正在查看这篇文章 。

  2. You need to have Node installed.

    您需要安装Node 。

To check if you have Node installed, open up your command line and run the following code:

要检查是否已安装Node,请打开命令行并运行以下代码:

$ node -v

You should get a version number if you have Node installed. If you don’t, you can install Node either by downloading the installer from Node’s website or downloading it through package managers like Homebrew (Mac) and Chocolatey (Windows).

如果安装了Node,则应该获得版本号。 如果不这样做,则可以通过从Node网站下载安装程序或通过Homebrew (Mac)和Chocolatey (Windows)等程序包管理器下载Node来安装Node。

入门 (Getting started)

Start by creating a folder for this project. Feel free to call it anything you want. Once you navigate into it, run the npm init command.

首先为该项目创建一个文件夹。 随时随地调用它即可。 导航到它之后,运行npm init命令。

This command creates a package.json file which helps you manage dependencies that we install later in the tutorial.

该命令将创建一个package.json文件,该文件可帮助您管理我们稍后将在本教程中安装的依赖项。

$ npm init

Just hit enter through everything that appears. I’ll talk about the ones you need to know as we go along.

只需按Enter即可出现的所有内容。 我将在讨论过程中谈论您需要了解的内容。

一生中第一次运行Node (Running Node for the first time in your life)

The simplest way to use node is to run the node command, and specify a path to a file. Let’s create a file called server.js to run node with.

使用节点的最简单方法是运行node命令,并指定文件的路径。 让我们创建一个名为server.js的文件以运行node。

$ touch server.js

When the execute the server.js file, we want to make sure it’s running properly. To do so, simply write a console.log statement in server.js:

执行server.js文件时,我们要确保其运行正常。 为此,只需在server.js中编写console.log语句:

console.log('May Node be with you')

Now, run node server.js in your command line and you should see the statement you logged:

现在,在命令行中运行node server.js,您应该看到记录的语句:

Great. Let’s move on and learn how to use Express now.

大。 让我们继续学习现在如何使用Express。

使用快递 (Using Express)

We first have to install Express before we can use it in our application. Installing Express is pretty easy. All we have to do is run an install command with Node package manager (npm),which comes bundled with Node.

我们必须先安装Express,然后才能在应用程序中使用它。 安装Express非常简单。 我们要做的就是使用Node软件包管理器(npm)运行安装命令,该软件包与Node捆绑在一起。

Run the npm install express — save command in your command line:

运行npm install express —在命令行中保存命令:

$ npm install express --save

Once you’re done, you should see that npm has saved Express as a dependency in package.json.

完成后,您应该看到npm已将Express保存为package.json中的依赖项。

Next, we use express in server.js by requiring it.

接下来,我们通过要求在server.js中使用express。

const express = require('express');const app = express();

The first thing we want to do is to create a server where browsers can connect to. We can do so with the help of a listen method provided by Express:

我们要做的第一件事是创建一个浏览器可以连接到的服务器。 我们可以借助Express提供的listen方法来做到这一点:

app.listen(3000, function() {  console.log('listening on 3000')})

Now, run node server.js and navigate to localhost:3000 on your browser. You should see a message that says “cannot get /”.

现在,运行节点server.js并在浏览器上导航到localhost:3000。 您应该看到一条消息“无法获取/”。

That’s a good sign. It means we can now communicate to our express server through the browser. This is where we begin CRUD operations.

这是一个好兆头。 这意味着我们现在可以通过浏览器与快递服务器通信 。 这是我们开始CRUD操作的地方。

CRUD —阅读 (CRUD — READ)

The READ operation is performed by browsers whenever you visit a webpage. Under the hood, browsers sends a GET request to the server to perform a READ operation. The reason we see the “cannot get /” error is because we have yet to send anything back to the browser from our server.

每当您访问网页时,浏览器都会执行READ操作。 在后台,浏览器将GET请求发送到服务器以执行READ操作。 我们看到“无法获取/”错误的原因是因为我们尚未将任何内容从服务器发送回浏览器。

In Express, we handle a GET request with the get method:

在Express中,我们使用get方法处理GET请求:

app.get(path, callback)

The first argument, path, is the path of the GET request. It’s anything that comes after your domain name.

第一个参数path是GET请求的路径。 域名之后的任何内容。

When we’re visiting localhost:3000, our browsers are actually looking for localhost:3000/. The path argument in this case is /.

当我们访问localhost:3000时,我们的浏览器实际上正在寻找localhost:3000 /。 在这种情况下,路径参数为/。

The second argument is a callback function that tells the server what to do when the path is matched. It takes in two arguments, a request object and a response object:

第二个参数是一个回调函数 ,它告诉服务器当路径匹配时该怎么做。 它接受两个参数,一个请求对象和一个响应对象:

app.get('/', function (request, response) {  // do something here})

For now, let’s write “Hello World” back to the browser. We do so by using a send method that comes with the response object:

现在,让我们将“ Hello World”写回到浏览器。 为此,我们使用了响应对象随附的send方法:

app.get('/', function(req, res) {  res.send('Hello World')})// Note: request and response are usually written as req and res respectively.

I’m going to start writing in ES6 code and show you how to convert to ES6 along the way as well. First off, I’m replacing the function() with the ES6 arrow function. The below code is the same as the above code:

我将开始编写ES6代码,并向您展示如何转换为ES6。 首先,我要用ES6箭头函数替换function()。 下面的代码与上面的代码相同:

app.get('/', (req, res) => {  res.send('hello world')})

Now, restart your server by doing the following:

现在,通过执行以下操作重新启动服务器:

  1. Stop the current server by hitting CTRL + C in the command line.
    通过在命令行中按CTRL + C来停止当前服务器。
  2. Run node server.js again.
    再次运行节点server.js。

Then, navigate to localhost:3000 on your browser. You should be able to see a string that says “Hello World”.

然后,在浏览器上导航到localhost:3000。 您应该能够看到显示“ Hello World”的字符串。

Great. Let’s change our app so we serve an index.html page back to the browser instead. To do so, we use the sendFile method that’s provided by the res object.

大。 让我们更改应用程序,以便将index.html页面提供回浏览器。 为此,我们使用res对象提供的sendFile方法。

app.get('/', (req, res) => {  res.sendFile(__dirname + '/index.html')  // Note: __dirname is the path to your current working directory. Try logging it and see what you get!   // Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.})

In the sendFile method above, we told Express to serve an index.html file that can be found in the root of your project folder. We don’t have that file yet. Let’s make it now.

在上面的sendFile方法中,我们告诉Express提供一个index.html文件,该文件可以在您的项目文件夹的根目录中找到。 我们还没有那个文件。 现在开始吧。

touch index.html

Let’s put some text in our index.html file as well:

我们也将一些文本放入我们的index.html文件中:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>MY APP</title></head><body>  May Node and Express be with you.   </body></html>

Restart your server and refresh your browser. You should be able to see the results of your HTML file now.

重新启动服务器并刷新浏览器。 您现在应该可以看到HTML文件的结果。

This is how Express handles a GET request (READ operation) in a nutshell.

简而言之,这就是Express处理GET请求( READ操作)的方式。

At this point, you probably have realized that you need to restart your server whenever you make a change to server.js. This is process is incredibly tedious, so let’s take a quick detour and streamline it by using a package called nodemon.

至此,您可能已经意识到,只要更改server.js,就需要重新启动服务器。 这个过程非常繁琐,因此让我们快速绕道并使用一个名为nodemon的包来简化它。

输入Nodemon (Enter Nodemon)

Nodemon restarts the server automatically whenever you save a file that the server uses. We can install Nodemon by using the following command:

每当您保存服务器使用的文件时, Nodemon都会自动重新启动服务器。 我们可以使用以下命令来安装Nodemon:

$ npm install nodemon --save-dev

Note: The reason we’re using a — save-dev flag here is because we’re only using Nodemon when we’re developing. This flag would save Nodemon as a devDependency in your package.json file.

注意:我们在这里使用一个save-dev标志的原因是因为我们仅在开发时使用Nodemon。 此标志会将Nodemon保存为package.json文件中的devDependency。

Moving on, Nodemon behaves exactly the same as node, which means we can run our server by calling nodemon server.js. However, we can’t do it in the command line right now because Nodemon isn’t installed with a -g flag.

接下来,Nodemon的行为与节点完全相同,这意味着我们可以通过调用nodemon server.js来运行服务器。 但是,由于Nodemon未安装-g标志,因此我们现在无法在命令行中执行此操作。

There’s one other way to run Nodemon — we can execute Nodemon from the node_modules folder. The code looks like this:

还有另一种运行Nodemon的方法-我们可以从node_modules文件夹执行Nodemon。 代码如下:

$ ./node_modules/.bin/nodemon server.js

That’s a handful to type. One way to make it simpler is to create a script key in package.json.

键入很少。 一种简化的方法是在package.json中创建脚本密钥。

{  // ...   "scripts": {    "dev": "nodemon server.js"  }  // ...}

Now, you can run npm run dev to trigger nodemon server.js.

现在,您可以运行npm run dev来触发nodemon server.js。

Back to the main topic. We’re going to cover the CREATE operation next.

回到主要话题。 接下来,我们将介绍CREATE操作。

CRUD —创建 (CRUD — CREATE)

The CREATE operation is performed only by the browser if a POST request is sent to the server. This POST request can triggered either with JavaScript or through a <form> element.

如果将POST请求发送到服务器,则仅由浏览器执行CREATE操作。 可以使用JavaScript或通过<form>元素触发此POST请求。

Let’s find out how to use a <form> element to create new entries for our star wars quote app for this part of the tutorial.

让我们找出如何使用<form>元素为教程的这一部分为我们的《星球大战》报价应用程序创建新条目。

To do so, you first have to create a <form> element and add it to your index.html file. You need to have three things on this form element:

为此,您首先必须创建一个<form>元素并将其添加到index.html文件中。 您需要在此表单元素上包含三件事:

  1. An action attribute
    动作属性
  2. a method attribute
    方法属性
  3. and name attributes on all <input> elements within the form
    和名称属性在表单中的所有<input>元素上
<form action="/quotes" method="POST">  <input type="text" placeholder="name" name="name">  <input type="text" placeholder="quote" name="quote">  <button type="submit">Submit</button></form>

The action attribute tells the browser where to navigate to in our Express app. In this case, we’re navigating to /quotes. The method attribute tells the browser what to request to send. In this case, it’s a POST request.

action属性告诉浏览器在我们Express应用中的导航位置。 在这种情况下,我们导航到/ quotes。 method属性告诉浏览器要发送什么请求。 在这种情况下,这是一个POST请求。

On our server, we can handle this POST request with a post method that Express provides. It takes the same arguments as the GET method:

在我们的服务器上,我们可以使用Express提供的post方法处理该POST请求。 它采用与GET方法相同的参数:

app.post('/quotes', (req, res) => {  console.log('Hellooooooooooooooooo!')})

Restart your server (hopefully you’ve set up Nodemon so it restarts automatically) and refresh your browser. Then, enter something into your form element. You should be able to see Hellooooooooooooooooo! in your command line.

重新启动服务器(希望您已设置Nodemon,使其自动重新启动)并刷新浏览器。 然后,在表单元素中输入一些内容。 您应该能够看到Hellooooooooooooooooo! 在您的命令行中。

Great, we know that Express is handling the form for us right now. The next question is, how do we get the input values with Express?

太好了,我们知道Express正在为我们处理表格。 下一个问题是,如何使用Express获得输入值?

Turns out, Express doesn’t handle reading data from the <form> element on it’s own. We have to add another package called body-parser to gain this functionality.

事实证明,Express本身并不处理从<form>元素读取数据。 我们必须添加另一个程序包主体分析器才能获得此功能。

$ npm install body-parser --save

Express allows us to add middlewares like body-parser to our application with the use method. You’ll hear the term middleware a lot when dealing with Express. These things are basically plugins that change the request or response object before they get handled by our application. Make sure you place body-parser before your CRUD handlers!

Express允许我们使用use方法向我们的应用程序中添加诸如body-parser之类的中间件。 在处理Express时,您会听到很多术语“中间件”。 这些东西基本上是在我们的应用程序处理它们之前更改请求或响应对象的插件。 确保将正文解析器放在CRUD处理程序之前!

const express = require('express')const bodyParser= require('body-parser')const app = express()
app.use(bodyParser.urlencoded({extended: true}))
// All your handlers here...

The urlencoded method within body-parser tells body-parser to extract data from the <form> element and add them to the body property in the request object.

body-parser中的urlencoded方法告诉body-parser从<form>元素中提取数据并将其添加到请求对象的body属性中。

Now, you should be able to see everything in the form field within the req.body object. Try doing a console.log and see what it is!

现在,您应该能够在req.body对象内的form字段中看到所有内容。 尝试做一个console.log,看看它是什么!

app.post('/quotes', (req, res) => {  console.log(req.body)})

You should be able to get an object similar to the following in your command line:

您应该能够在命令行中获得类似于以下内容的对象:

Hmmm. Master Yoda has spoken! Let’s make sure we remember Yoda’s words. It’s important. We want to be able to retrieve it the next time we load our index page.

嗯 尤达大师讲话! 让我们确保我们记得尤达的话。 这一点很重要。 我们希望下次加载索引页面时能够检索它。

Enter the database, MongoDB.

输入数据库MongoDB。

MongoDB (MongoDB)

We first have to install MongoDB through npm if we want to use it as our database.

如果要使用MongoDB作为数据库,首先必须通过npm安装它。

npm install mongodb --save

Once installed, we can connect to MongoDB through the Mongo.Client‘s connect method as shown in the code below:

安装后,我们可以通过Mongo.Client的connect方法连接到MongoDB,如下代码所示:

const MongoClient = require('mongodb').MongoClient
MongoClient.connect('link-to-mongodb', (err, database) => {  // ... start the server})

The next part is to get the correct link to our database. Most people store their databases on cloud services like MongoLab. We’re going to do same as well.

下一部分是获得到我们数据库的正确链接。 大多数人将其数据库存储在MongoLab等云服务上。 我们也将做同样的事情。

So, go ahead and create an account with MongoLab. (It’s free). Once you’re done, create a new MongoDB Deployment and set the plan to sandbox.

因此,继续使用MongoLab创建一个帐户。 (免费)。 完成后,创建一个新的MongoDB部署并将计划设置为沙箱。

Once you’re done creating the deployment, head into it and create a database user and database password. Remember the database user and database password because you’re going to use it to connect the database you’ve just created.

创建完部署后,请进入部署并创建数据库用户和数据库密码。 记住数据库用户和数据库密码,因为您将使用它来连接刚刚创建的数据库。

Finally, grab the MongoDB url and add it to your MongoClient.connect method. Make sure you use your database user and password!

最后,获取MongoDB网址并将其添加到您的MongoClient.connect方法中。 确保使用数据库用户名和密码!

MongoClient.connect('your-mongodb-url', (err, database) => {  // ... do something here})

Next, we want to start our servers only when the database is connected. Hence, let’s move app.listen into the connect method. We’re also going to create a db variable to allow us to use the database when we handle requests from the browser.

接下来,我们只想在连接数据库时启动服务器。 因此,让我们将app.listen移到connect方法中。 我们还将创建一个db变量,以允许我们在处理来自浏览器的请求时使用数据库。

var db
MongoClient.connect('your-mongodb-url', (err, database) => {  if (err) return console.log(err)  db = database  app.listen(3000, () => {    console.log('listening on 3000')  })})

We’re done setting up MongoDB. Now, let’s create a quotes collection to store quotes for our application.

我们已经完成了MongoDB的设置。 现在,让我们创建一个quotes集合来存储我们的应用程序的报价。

By the way, a collection is a named location to store stuff. You can create as many collections as you want. It can be things like “products”, “quotes”, “groceries”, or any other labels you choose.

顺便说一句, 集合是存储东西的命名位置 。 您可以根据需要创建任意多个集合。 可以是诸如“产品”,“报价”,“杂货”或您选择的任何其他标签之类的东西。

We can create the quotes collection by using the string quotes while calling MongoDB’s db.collection() method. While creating the quotes collection, we can also save our first entry into MongoDB with the save method simultaneously.

我们可以在调用MongoDB的db.collection()方法时使用字符串引号创建引号集合。 在创建报价集合时,我们还可以使用save方法将第一个条目同时保存到MongoDB中。

Once we’re done saving, we have to redirect the user somewhere (or they’ll be stuck waiting forever for our server to move). In this case, we’re going to redirect them back to /, which causes their browsers to reload.

保存完成后,我们必须将用户重定向到某个位置 (否则,他们将永远被困在等待服务器移动的位置)。 在这种情况下,我们将其重定向回/,这将导致其浏览器重新加载。

app.post('/quotes', (req, res) => {  db.collection('quotes').save(req.body, (err, result) => {    if (err) return console.log(err)
console.log('saved to database')    res.redirect('/')  })})

Now, if you enter something into the <form> element, you’ll be able to see an entry in your MongoDB collection.

现在,如果您在<form>元素中输入内容,您将能够在MongoDB集合中看到一个条目。

Whoohoo! Since we already have some quotes in the collection, why not try showing them to our user when they land on our page?

hoo! 既然我们已经在集合中包含了一些报价,那么为什么不尝试在用户登陆我们的页面时将其显示给用户呢?

向用户显示报价 (Showing quotes to users)

We have to do two things to show the quotes stored in MongoLab to our users.

我们必须做两件事才能向用户显示MongoLab中存储的报价。

  1. Get quotes from MongoLab
    获得MongoLab的报价
  2. Use a template engine to display the quotes
    使用模板引擎显示报价

Let’s go one step at a time.

让我们一次走一步。

We can get the quotes from MongoLab by using the find method that’s available in the collection method.

我们可以使用collection方法中可用的find方法从MongoLab获取报价。

app.get('/', (req, res) => {  var cursor = db.collection('quotes').find()})

The find method returns a cursor (A Mongo Object) that probably doesn’t make sense if you console.log it out.

find方法返回一个游标(一个Mongo对象),如果您进行console.log out,则该游标可能没有任何意义。

The good news is, this cursor object contains all quotes from our database. It also contains a bunch of other properties and methods that allow us to work with data easily. One such method is the toArray method.

好消息是,此游标对象包含我们数据库中的所有引号。 它还包含许多其他属性和方法,这些属性和方法使我们可以轻松地处理数据。 一种这样的方法是toArray方法。

The toArray method takes in a callback function that allows us to do stuff with quotes we retrieved from MongoLab. Let’s try doing a console.log() for the results and see what we get!

toArray方法带有一个回调函数,该函数允许我们使用从MongoLab检索到的引号进行处理。 让我们尝试对结果进行console.log()看看我们得到了什么!

db.collection('quotes').find().toArray(function(err, results) {  console.log(results)  // send HTML file populated with quotes here})

Great! You now see an array of quotes (I only have one right now). We’ve completed the first part — getting data from MongoLab. The next part is to generate a HTML that contains all our quotes.

大! 现在,您会看到一组引号(我现在只有一个)。 我们已经完成了第一部分-从MongoLab获取数据。 下一部分是生成包含所有引号HTML。

We can’t serve our index.html file and expect quotes to magically appear because there’s no way to add dynamic content to a HTML file. What we can do instead, is to use template engines to help us out. Some popular template engines include Jade, Embedded JavaScript and Nunjucks.

我们无法提供index.html文件,不能期望引号神奇地出现,因为无法将动态内容添加到HTML文件中。 我们可以做的是使用模板引擎来帮助我们。 一些流行的模板引擎包括Jade,嵌入式JavaScript和Nunjucks。

I’ve written extensively about the how and why of template engines in a separate post. You might want to check it out if you have no idea what template engines are. I personally use (and recommend) Nunjucks as my template engine of choice. Feel free to check out the post to find out why.

我在另一篇文章中广泛地介绍了模板引擎的方式和原因。 如果您不知道什么是模板引擎,则可能需要检查一下。 我个人使用(并推荐)Nunjucks作为我选择的模板引擎。 随时查看该帖子以了解原因。

For this tutorial, we’re going to use Embedded JavaScript (ejs) as our template engine because it’s the easiest to start with. You’ll find it familiar from the get-go since you already know HTML and JavaScript.

在本教程中,我们将使用嵌入式JavaScript (ejs)作为模板引擎,因为它是最简单的开始。 从一开始,您就会发现它很熟悉,因为您已经了解HTML和JavaScript。

We can use EJS by first installing it, then setting the view engine in Express to ejs.

我们可以先安装EJS,然后将Express中的视图引擎设置为ejs来使用。

$ npm install ejs --save
app.set('view engine', 'ejs')

Once the view engine is set, we can begin generating the HTML with our quotes. This process is also called rendering. We can use the render object built into the response object render to do so. It has the following syntax:

设置视图引擎后,我们就可以开始使用引号来生成HTML了。 此过程也称为渲染 。 我们可以使用内置在响应对象render中的render对象来做到这一点。 它具有以下语法:

res.render(view, locals)

The first parameter, views, is the name of the file we’re rendering. This file must be placed within a views folder.

第一个参数views是我们正在渲染的文件的名称。 该文件必须放置在views文件夹中。

The second parameter, locals, is an object that passes data into the view.

第二个参数locals是一个将数据传递到视图的对象。

Let’s first create an index.ejs file within the views folder so we can start populating data.

首先让我们在views文件夹中创建一个index.ejs文件,以便我们可以开始填充数据。

$ mkdir views$ touch views/index.ejs

Now, place the following code within index.ejs.

现在,将以下代码放入index.ejs中。

<ul class="quotes">  <% for(var i=0; i<quotes.length; i++) {%>    <li class="quote">      <span><%= quotes[i].name %></span>      <span><%= quotes[i].quote %></span>    </li>  <% } %></ul>

See what I mean when I say you’ll find it familiar? In EJS, you can write JavaScript within <% and %> tags. You can also output JavaScript as strings if you use the <%= and %> tags.

明白当我说您会觉得熟悉时的意思吗? 在EJS中,您可以在<%和%>标记内编写JavaScript。 如果使用<%=和%>标记,还可以将JavaScript输出为字符串。

Here, you can see that we’re basically looping through the quotes array and create strings with quotes[i].name and quotes[i].quote.

在这里,您可以看到我们基本上遍历了quotes数组,并创建了带有quotes [i] .name和quotes [i] .quote的字符串。

One more thing to do before we move on from the index.ejs file. Remember to copy the <form> element from the index.html file into this file as well. The complete index.ejs file so far should be:

从index.ejs文件继续之前,还有另一件事要做。 切记也将<form>元素也从index.html文件复制到该文件中。 到目前为止,完整的index.ejs文件应为:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>MY APP</title></head><body>  May Node and Express be with you.
<ul class="quotes">  <% for(var i=0; i<quotes.length; i++) {%>    <li class="quote">      <span><%= quotes[i].name %></span>      <span><%= quotes[i].quote %></span>    </li>  <% } %>  </ul>
<form action="/quotes" method="POST">    <input type="text" placeholder="name" name="name">    <input type="text" placeholder="quote" name="quote">    <button type="submit">Submit</button>  </form></body></html>

Finally, we have to render this index.ejs file when handling the GET request. Here, we’re setting the results (an array) as the quotes array we used in index.ejs above.

最后,我们必须在处理GET请求时呈现此index.ejs文件。 在这里,我们将结果(一个数组)设置为上面index.ejs中使用的引号数组。

app.get('/', (req, res) => {  db.collection('quotes').find().toArray((err, result) => {    if (err) return console.log(err)    // renders index.ejs    res.render('index.ejs', {quotes: result})  })})

Now, refresh your browser and you should be able to see Master Yoda’s quotes.

现在,刷新浏览器,您应该能够看到Yoda大师的报价。

Um. You maybe only have one quote if you followed the tutorial step by step until this point. The reason I have multiple quotes is because I silently added more as I worked on the application.

嗯 如果您逐步按照本教程进行操作,则可能只有一个报价。 我有多个引号的原因是因为我在处理该应用程序时默默地添加了更多内容。

结语 (Wrapping Up)

We’ve covered a lot of ground in just 3000 words. Here are a few bullets to sum it all up. You have…

我们仅用3000个字就覆盖了很多领域。 这里总结了一些项目符号。 你有…

  • Created an Express Server
    创建一个Express服务器
  • Learned to execute CREATE and READ operations
    学习执行CREATE和READ操作
  • Learned to save and read from MongoDB
    学会保存和从MongoDB中读取
  • Learned to use a template engine like Embedded JS.
    了解如何使用模板引擎,例如Embedded JS。

There are two more operations to go, but we’ll leave it to the next post. Catch you there!

还有两个操作要做,但我们将其留在下一篇文章中。 赶上你!

This article first appeared on my blog at www.zell-weekeat.com. Check it out if you want more articles like this

这篇文章首先出现在我的博客www.zell-weekeat.com上 。 如果您想要更多这样的文章,请查看

翻译自: https://www.freecodecamp.org/news/building-a-simple-crud-application-with-express-and-mongodb-63f80f3eb1cd/

使用Express和MongoDB构建简单的CRUD应用程序相关推荐

  1. 使用Express和MongoDB构建CRUD应用程序-第2部分

    by Zell Liew 由Zell Liew 使用Express和MongoDB构建CRUD应用程序-第2部分 (Building a CRUD Application with Express a ...

  2. Flash AS3.0实例教程:构建简单的声音可视化程序(波型图)

    本例为Flash AS3.0实例教程,在教程中我们将学习运用SoundMixer.computeSpectrum() 方法来构建简单的声音可视化程序(即波形图),希望能给朋友们带来帮助~~ AS3.0 ...

  3. beta应用程序ios_通过构建简单的食谱应用程序来了解iOS最佳做法

    beta应用程序ios by Khoa Pham 通过Khoa Pham 通过构建简单的食谱应用程序来了解iOS最佳做法 (Learn iOS best practices by building a ...

  4. 使用Spring Boot和MongoDB构建一个React式应用程序

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 如果您要 ...

  5. 使用Spring Boot和MongoDB构建一个反应式应用程序

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 如果您要 ...

  6. 使用React和Spring Boot构建一个简单的CRUD应用

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. Reac ...

  7. 使用 Node.js、Express、AngularJS 和 MongoDB 构建一个Web程序

    为什么80%的码农都做不了架构师?>>>    使用 Node.js.Express.AngularJS 和 MongoDB 构建一个实时问卷调查应用程序 2014 年 3 月 20 ...

  8. react和nodejs_如何使用React,TypeScript,NodeJS和MongoDB构建Todo应用

    react和nodejs In this tutorial, we will be using TypeScript on both sides (server and client) to buil ...

  9. angular1.2.27_Angular 8 + Spring Boot 2.2:立即构建一个CRUD应用程序!

    angular1.2.27 "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权 ...

最新文章

  1. 8、显示程序占用内存多少.txt
  2. redis4.0之基于LFU的热点key发现机制
  3. eureka客户端获取服务列表时间间隔配置
  4. mysql illegal mix of_mysql字符集问题:Illegal mix of collations
  5. css3--文字效果
  6. linux下面拷贝gbk编码的网页
  7. js 判断移动端还是pc端,ios或者android
  8. 项目合作| 视频监控解决隧道洗车线的安全问题
  9. pandas frame 删除一行_Pandas如何处理大规模数据?
  10. 手机微信html整人代码大全,让微信卡死的代码是什么 微信整人代码汇总
  11. mysql授权远程访问 网段_MySQL授权和开启远程访问
  12. 用ajax来上传图片,使用AJAX上传图片
  13. 串口485接法图_485串口接线
  14. [CAN BUS] USB-CAN adpter / USB转CAN 开源项目推荐(CANable candlelight cangaroo)
  15. 深入理解地球的经度和纬度换算
  16. 计算机控制面板设置命令,控制面板在哪?控制面板命令,5种控制面板快速打开法...
  17. 电脑开启移动热点手机一直显示正在获取ip
  18. C++ Templates中文版 p61页的一个问题
  19. 1086 Tree Traversals Again (25分)
  20. 大学生html5实训心得体会,实训心得体会600字(精选5篇)

热门文章

  1. 组件化与插件化的差别在哪里?内含福利
  2. java注解编程_Java注解编程原理
  3. 微信小程序之视图容器(swiper)组件创建轮播图
  4. java并发编程实战:第十四章----构建自定义的同步工具
  5. 几种机器学习算法的优缺点
  6. 12.8 线程和信号
  7. SPRING IN ACTION 第4版笔记-第二章-002-@ComponentScan、@Autowired的用法
  8. 关于tomcat内路径跳转的一些思考
  9. 【iOS开发每日小笔记(一)】UIPickerView 自动选择某个component的某个row
  10. (3)[wp7数据存储] WP7 IsolatedStorage系列篇——通过XmlSerializer读写XML文件 [复制链接]...