1.安装express
npm install express --save
2.安装成功后利用 express创建项目
express -e 名称
npm i
3.创建数据库链接 db.js
module.exports = function(s,c){
const mongoose =require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/数据库名称')
mongoose.connection.once('open',()=>{
console.log('打开提示')
s()
})//打开提示
mongoose.connection.once('error',()=>{
console.log('错误提示')
c()
})//错误提示
mongoose.connection.once('close',()=>{
console.log('关闭提示')
})//关闭提示
}
4.创建表字段 user.js
npm install mongoose安装 mongoose
const mongoose =require('mongoose');
let rega =new mongoose.Schema({
user : String,
pass : String,
})
let reg = mongoose.model('表名',rega )
module.exports = reg
5.插入数据 (在配置路由规则中) index.js
router.post('/home', function(req, res, next) {
console.log(req.body)
//插入数据
bigb.create({
...req.body
}).then((data)=>{
console.log(data);
})
//查询数据
bigb.find().then((data)=>{
console.log(data);
res.render('page',{neirong:data})
});
});
5.1 提交数据 login.ejs
<body>
<form action="http://127.0.0.1:3000/home" method="POST" >
<input name="user" type="text">
<input name="pass" type="password">
<button type="submit">登录</button>
</body>
6.启动项目
npm start
127.0.0.1:3000/home