mongoose与express

一、mongoose的使用
1.先创建一个项目目录,初始化:npm init -y
2.创建一个server.js文件,在该目录下安装mongoose:cnpm install mongoose
3.引入mongoose模块,并用connect方法连接到数据库(地址的最后面是数据库的名字):
  const mongoose = require("mongoose");
  mongoose.connect("mongodb://127.0.0.1:27017/BK1824",(err)=>{})
4.需要先定义数据表中字段的类型(mongoose在创建表时会在后面加上s,即此时的student表实际上是students表,且字段的类型必须是大写的):
  const User = mongoose.model("student",{
    name:String,
    sex:String,
    age:Number
  })
5.增加数据:
  const user1 = new User({name:"aaa",sex:"aaa",age:20});
  user1.save().then((res)=>{consoe.log(res);});//res返回的是增加的数据
6.删除数据:
  User.remove({name:"aaa"}).then((res)=>{console.log(res);});//res返回的是受影响的行数
7.改变数据:
  User.update({name:"aaa"},{$set:{sex:"bbb"},$inc:{age:10}}).then((res)=>{consle.log(res);})//res返回的是受影响的行数
8.查找数据(所有数据)
  User.find().then((res)=>{console.log(res);})//res返回查找到的数据
二、express
1.新建一个目录如express,进入打开终端并初始化:npm init -y
2.在express目录下局部安装express模块:cnpm install express -S
3.在express目录下新建index.js文件,引入express模块,并绑定端口号:
  const express = require("express");
  const app = express();
  app.get("/",(req,res)=>{//当访问根路径时返回“Hello World!”
    res.send("Hello World!");
  })
  app.listen(3000,()=>{//绑定端口
    console.log("端口已绑定");
  })
三、express应用程序生成器
1.新建项目目录如demo,进入并安装应用程序生成器:express -e
2.安装依赖文件:npm install
3.在package.json文件中的scripts可以找到启动命令:npm start
4.当页面刷新时会在终端显示调试的提示信息
5.routes中的index.js中的res.render表示页面的渲染,里面的第一个参数表示express会先去寻找public文件夹中的index.html文件,如果没有则寻找views文件夹中的index.ejs文件
四、ejs文件对于页面的渲染
1.<%= %>数据的渲染
2.<%- %>解析HTML标签
3.<% %>业务逻辑:if、for
4.<%% %%>转义字符
5.<%- include("./header.ejs") %>引入其他ejs模板

猜你喜欢

转载自www.cnblogs.com/Leslie-Cheung1584304774/p/10544114.html