ExpressJS - 数据库
我们不断收到请求,但最终却没有将它们存储在任何地方。我们需要一个数据库来存储数据。为此,我们将使用名为 MongoDB 的 NoSQL 数据库。
要安装和了解 Mongo,请点击此链接。
为了将 Mongo 与 Express 结合使用,我们需要一个用于节点的客户端 API。我们有多种选择,但在本教程中,我们将坚持使用 mongoose。Mongoose 用于 MongoDB 中 Node 中的文档建模。对于文档建模,我们创建一个模型(非常类似于面向文档编程中的类),然后我们使用此模型生成文档(就像我们在 OOP 中创建类的文档一样)。我们所有的处理都将在这些"文档"上完成,最后,我们将这些文档写入我们的数据库。
设置 Mongoose
现在您已经安装了 Mongo,让我们安装 Mongoose,就像我们安装其他节点包一样 −
npm install --save mongoose
在开始使用 mongoose 之前,我们必须使用 Mongo shell 创建一个数据库。要创建新数据库,请打开您的终端并输入"mongo"。 Mongo shell 将启动,输入以下代码 −
use my_db
将为您创建一个新数据库。每当您打开 mongo shell 时,它将默认为"test"db,您必须使用与上述相同的命令更改为您的数据库。
要使用 Mongoose,我们将在 index.js 文件中需要它,然后连接到在 mongodb://localhost 上运行的 mongodb 服务。
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db');
现在我们的应用程序已连接到我们的数据库,让我们创建一个新的模型。该模型将充当我们数据库中的集合。要创建新模型,请在定义任何路线之前使用以下代码 −
var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema);
上述代码定义了人员的架构,用于创建 Mongoose 模式 Person。
保存文档
现在,我们将创建一个新的 html 表单;此表单将帮助您获取人员的详细信息并将其保存到我们的数据库中。要创建表单,请在 views 目录中创建一个名为 person.pug 的新视图文件,其中包含以下内容 −
html head title Person body form(action = "/person", method = "POST") div label(for = "name") Name: input(name = "name") br div label(for = "age") Age: input(name = "age") br div label(for = "nationality") Nationality: input(name = "nationality") br button(type = "submit") Create new person
同时在 index.js 中添加一个 new get route 来呈现此文档 −
app.get('/person', function(req, res){ res.render('person'); });
转到"localhost:3000/person"以检查表单是否显示正确的输出。请注意,这只是 UI,它尚未工作。以下屏幕截图显示了表单的显示方式 −
我们现在将在 '/person' 处定义一个 post 路由处理程序来处理此请求
app.post('/person', function(req, res){ var personInfo = req.body; //Get the parsed information if(!personInfo.name || !personInfo.age || !personInfo.nationality){ res.render('show_message', { message: "Sorry, you provided worng info", type: "error"}); } else { var newPerson = new Person({ name: personInfo.name, age: personInfo.age, nationality: personInfo.nationality }); newPerson.save(function(err, Person){ if(err) res.render('show_message', {message: "Database error", type: "error"}); else res.render('show_message', { message: "New person added", type: "success", person: personInfo}); }); } });
在上面的代码中,如果我们收到任何空字段或没有收到任何字段,我们将发送错误响应。但是,如果我们收到格式正确的文档,则我们从 Person 模型创建一个 newPerson 文档,并使用 newPerson.save() 函数将其保存到我们的数据库中。这是在 Mongoose 中定义的,并接受回调作为参数。此回调有 2 个参数 - 错误和响应。这些参数将呈现 show_message 视图。
要显示来自此路由的响应,我们还需要创建一个 show_message 视图。使用以下代码创建一个新视图 −
html head title Person body if(type == "error") h3(style = "color:red") #{message} else h3 New person, name: #{person.name}, age: #{person.age} and nationality: #{person.nationality} added!
成功提交 form(show_message.pug) 后,我们将收到以下响应 −
我们现在有一个创建 persons 的接口。
检索文档
Mongoose 提供了很多用于检索文档的函数,我们将重点介绍其中的 3 个。所有这些函数也将回调作为最后一个参数,并且与 save 函数一样,它们的参数是 error 和 response。这三个函数如下 −
Model.find(conditions, callback)
此函数查找与 conditions 对象中的字段匹配的所有文档。Mongo 中使用的相同运算符也适用于 mongoose。例如,
Person.find(function(err, response){ console.log(response); });
这将从该人的收藏中获取所有文档。
Person.find({name: "Ayush", age: 20}, function(err, response){ console.log(response); });
这将获取字段名称为"Ayush"且年龄为 20 的所有文档。
我们还可以提供所需的投影,即所需的字段。例如,如果我们只想要国籍为"印度"的人的姓名,我们使用 −
Person.find({nationality: "Indian"}, "name", function(err, response){ console.log(response); });
Model.findOne(conditions, callback)
此函数始终获取单个最相关的文档。它具有与 Model.find() 完全相同的参数。
Model.findById(id, callback)
此函数将 _id(由 mongo 定义)作为第一个参数,一个可选的投影字符串和一个用于处理响应的回调。例如,
Person.findById("507f1f77bcf86cd799439011", function(err, response){ console.log(response); });
现在让我们创建一个查看所有人员记录的路线 −
var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.get('/people', function(req, res){ Person.find(function(err, response){ res.json(response); }); }); app.listen(3000);
更新文档
Mongoose 提供 3 个函数来更新文档。这些函数如下所述 −
Model.update(condition, updates, callback)
此函数接受条件并更新对象作为输入,并将更改应用于集合中符合条件的所有文档。例如,以下代码将更新所有 Person 文档中的国籍"American" −
Person.update({age: 25}, {nationality: "American"}, function(err, response){ console.log(response); });
Model.findOneAndUpdate(condition, updates, callback)
它根据查询找到一个文档,并根据第二个参数更新该文档。它还将回调作为最后一个参数。让我们执行以下示例来了解该函数
Person.findOneAndUpdate({name: "Ayush"}, {age: 40}, function(err, response) { console.log(response); });
Model.findByIdAndUpdate(id, updates, callback)
此函数更新由其 id 标识的单个文档。例如,
Person.findByIdAndUpdate("507f1f77bcf86cd799439011", {name: "James"}, function(err, response){ console.log(response); });
现在让我们创建一个更新人员的路由。这将是一个 PUT 路由,以 id 作为参数,并在有效负载中提供详细信息。
var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.put('/people/:id', function(req, res){ Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){ if(err) res.json({message: "Error in updating person with id " + req.params.id}); res.json(response); }); }); app.listen(3000);
要测试此路由,请在您的终端中输入以下内容(将 id 替换为您创建的 people 中的 id)−
curl -X PUT --data "name = James&age = 20&nationality = American "http://localhost:3000/people/507f1f77bcf86cd799439011
这将使用上述详细信息更新与路由中提供的 id 关联的文档。
删除文档
我们已经介绍了创建、读取和更新,现在我们将了解如何使用 Mongoose 来删除文档。这里有 3 个函数,与更新完全相同。
Model.remove(condition, [callback])
此函数将条件对象作为输入,并删除所有符合条件的文档。例如,如果我们需要删除所有 20 岁的人,请使用以下语法 −
Person.remove({age:20});
Model.findOneAndRemove(condition, [callback])
此函数根据条件对象删除单个最相关的文档。让我们执行以下代码来理解这一点。
Person.findOneAndRemove({name: "Ayush"});
Model.findByIdAndRemove(id, [callback])
此函数删除由其 id 标识的单个文档。例如,
Person.findByIdAndRemove("507f1f77bcf86cd799439011");
现在让我们创建一个从数据库中删除人员的路由。
var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.delete('/people/:id', function(req, res){ Person.findByIdAndRemove(req.params.id, function(err, response){ if(err) res.json({message: "Error in deleting record id " + req.params.id}); else res.json({message: "Person with id " + req.params.id + " removed."}); }); }); app.listen(3000);
要检查输出,请使用以下 curl 命令 −
curl -X DELETE http://localhost:3000/people/507f1f77bcf86cd799439011
这将删除具有给定 id 的人员,并生成以下消息 −
{message: "Person with id 507f1f77bcf86cd799439011 removed."}
这总结了如何使用 MongoDB、Mongoose 和 Express 创建简单的 CRUD 应用程序。要进一步探索 Mongoose,请阅读 API 文档。