案例:学生档案信息的填写,显示在表格中。
运行环境:node.js下的运行环境
1、准备工作
创建文件夹student,在student文件夹下创建4个目录
- public:静态资源
- views:模板页面
- model:数据库文件
- rotue:路由文件
2、使用http搭建web服务器
student根目录下创建app.js
// 引入http模块
const http = require('http');
// 创建网站服务器
const app = http.createServer();
// 当客户端访问服务器端的时候
app.on('request', (req, res) => {
res.end('ok');
});
// 端口监听
app.listen(80);
console.log('服务器启动成功...');
然后在student根目录下
按Shift+鼠标右键,打开powershell窗口,输入命令nodemon app.js
3、连接数据库
1.model文件夹 => connect.js
const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost/student', { useUnifiedTopology: true, useNewUrlParser: true })
.then(() => console.log('数据库连接成功...'))
.catch(() => console.log('数据库连接失败...'));
记得在app.js中写入,才能在执行命令nodemon app.js时连接到数据库
// 数据库连接
require('./model/connect');
2.model文件夹 =>uesr.js
连接到数据后就要创建集合规则规则啦,再根据规则创建集合。
const mongoose = require('mongoose');
// 创建学生集合规则
const studentsSchemat = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20
},
age: {
type: Number,
min: 10,
max: 25
},
sex: {
type: String
},
email: String,
hobbies: [String],
collage: String,
enterDate: {
type: Date,
default: Date.now
}
});
// 创建学生信息集合
const Student = mongoose.model('Student', studentsSchemat);
// 将学生信息集合进行导出
module.exports = Student;
4、创建路由
// 学生信息集合
const Student = require('../model/user');
// 引入router模块
const getRouter = require('router');
// 获取路由对象
const router = getRouter();
router.get('/list', async(req, res) => {
let students = await Student.find();
//console.log(students);
res.end('ok');
});
module.exports = router;