//数据库模式设计 Student.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Student',{
useNewUrlParser: true});
//设计学生数据库的模式
var StudentSchema = new mongoose.Schema({
Sno: {
type: String,
require: true
},
Name: {
type: String,
require: true
},
Age: {
type: Number,
require: true
},
Gender: {
type: Number,
require: true,
enum: [0,1]
},
Hobbies: {
type: String
}
});
//直接导出模型构造函数
module.exports = mongoose.model('Student',StudentSchema);
//router.js
var fs = require('fs');
var url = require('url');
var express = require('express');
/*
{
_id: 60827233984ce42cdc3c0385,
Sno: '12301',
Name: 'James',
Age: 18,
Gender: 1,
Hobbies: 'King of basketball',
__v: 0
}
*/
//获取封装各种调用函数的文件
var Student = require('./Student.js');
//创建路由器
var router = express.Router();
//路由容器,用来存放各种各样的路由
//主页面的views目录要和app.js目录同级
router.get('/',function(request,response){
//从文件中读取数据,(因为读取文件时,默认读取格式是16进制)第二个参数是文件传输格式,也可以选择用函数 data.toString()进行转换;
//500状态码,服务端出错状态码
/*
//根据条件查找文档,如果条件为空则查询所有数据
//返回的是一个数组,数组里的每一项为一个对象
//查询名叫张三的
User.find({name: '张三'}).then(result => console.log(result));
//查找年龄大于20小于30的
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result));
// 返回的是一个对象,默认返回当前集合中的第一条文档
User.findOne({name: '张三'}).then(result => console.log(result));
//对查找到的数据进行处理
// 查询所有数据中的指定字段
User.find().select('name email -_id').then(result => console.log(result));
// 根据年龄字段进行升序排列
User.find().sort('age').then(result => console.log(result));
// 根据年龄字段进行降序排列
User.find().sort('-age').then(result => console.log(result));
// 查询的数据跳过前两条结果 限制显示5条结果,通常用于数据的分页显示
User.find().skip(2).limit(5).then(result => console.log(result));
*/
Student.find(function(error , students){
if(error){
return response.status(500).send('Server error!');
}else{
response.render('index.html',{
Students: students
});
}
});
});
//Save保存学生的函数有两个参数:
/*
第一个参数: 包含学生信息的对象
第二个参数: 处理学生对象的回调函数
回调函数的参数:
第一个参数: error 参数,读取成功返回null,失败则返回一个对象
第二个参数:从文件中读出的包含students的data对象
*/
router.post('/add',function(request,response){
//用模式构造函数构造一个对象,接收post请求体的数据
var temp = new Student(request.body);
//将接收到的数据,保存进数据库
temp.save(function(error,result){
if(error){
return response.render('404.html');
}else{
//若新增的数据保存成功,则通过查询数据,并返回 ,Mongodb的模式构造函数的方法传回的查询结果传给回调函数,而不是模式构造函数本身
Student.find(function(error,result){
if(error){
return response.render('404.html');
}else{
return response.render('index.html',{
Students: result
})
}
});
}
});
});
/*
在用户点击编辑后,将相应id的学生信息返回服务端,服务端再渲染给编辑方框进行修改
*/
router.get('/edit',function(request,response){
let id = request.query.id;
//当收到edit请求之后,回调数据库的两个查找方法,重新渲染编辑列表以及展示列表
Student.findOne({
Sno: id
},function(error,result){
if(error){
response.render('404.html');
}else{
Student.find(function(error,students){
if(
06-04
374
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交