MEAN.JS 数据模型
在本章中,我们将演示如何在 Node-express 应用程序中使用数据模型。
MongoDB 是一个开源的 NoSQL 数据库,它以 JSON 格式保存数据。它使用面向文档的
数据模型来存储数据,而不是我们在关系数据库中使用的表和行。在本章中,我们将使用 Mongodb 来构建数据模型。
数据模型指定文档中存在哪些数据,以及文档中应该存在哪些数据。参考官方MongoDB安装,安装MongoDB。
我们将使用我们之前的章节代码。您可以在此链接中下载源代码。下载压缩文件;在您的系统中提取它。打开终端并运行以下命令安装 npm 模块依赖项。
$ cd mean-demo
$ npm install
将 Mongoose 添加到应用程序
Mongoose 是一个数据建模库,它通过使 MongoDB 变得强大来指定数据的环境和结构。您可以通过命令行将 Mongoose 安装为 npm 模块。转到您的根文件夹并运行以下命令-
$ npm install--save mongoose
上述命令将下载新包并将其安装到
node_modules 文件夹中。
--save 标志会将这个包添加到
package.json 文件中。
{
"name": "mean_tutorial",
"version": "1.0.0",
"description": "this is basic tutorial example for MEAN stack",
"main": "server.js",
"scripts": {
"test": "test"
},
"keywords": [
"MEAN",
"Mongo",
"Express",
"Angular",
"Nodejs"
],
"author": "Manisha",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.5.13"
}
}
设置连接文件
要使用数据模型,我们将使用
app/models 文件夹。让我们创建模型
students.js 如下-
var mongoose = require('mongoose');
// define our students model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('Student', {
name : {type : String, default: ''}
});
您可以通过创建文件并在应用程序中使用来设置连接文件。在
config/db.js 中创建一个名为
db.js 的文件。文件内容如下-
module.exports = {
url : 'mongodb://localhost:27017/test'
}
这里
test是数据库名称。
这里假设您已经在本地安装了 MongoDB。安装后启动 Mongo 并按名称 test 创建一个数据库。这个数据库将有一个名为学生的集合。向该集合中插入一些数据。在我们的例子中,我们使用 db.students.insertOne( { name: 'Manisha' , place: 'Pune', country: 'India'} );
将
db.js 文件引入应用程序,即在
server.js 中。内容 of 文件如下所示-
// modules =================================================
const express = require('express');
const app = express();
var mongoose = require('mongoose');
// set our port
const port = 3000;
// configuration ===========================================
// config files
var db = require('./config/db');
console.log("connecting--",db);
mongoose.connect(db.url); //Mongoose connection created
// frontend routes =========================================================
app.get('/', (req, res) ⇒ res.send('Welcome to Tutorialspoint!'));
//defining route
app.get('/tproute', function (req, res) {
res.send('this is routing for the application developed using Node and Express...');
});
// sample api route
// grab the student model we just created
var Student = require('./app/models/student');
app.get('/api/students', function(req, res) {
// use mongoose to get all students in the database
Student.find(function(err, students) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(students); // return all students in JSON format
});
});
// startup our app at http://localhost:3000
app.listen(port, () ⇒ console.log(`Example app listening on port ${port}!`));
接下来,使用以下命令运行应用程序-
您将收到如下图所示的确认-
现在,转到浏览器并输入
http://localhost:3000/api/students。您将获得如下图所示的页面-
