前言
大家好 我是歌谣 今天给大家带来的是MongoDB关于node操作数据库的讲解
依赖配置
需要安装express-genetator脚手架创建项目
配置文件
{
"name": "myapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ejs": "~2.6.1",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"mongoose": "^7.6.3",
"morgan": "~1.9.1"
}
}
文件目录
index.ejs
mongodb的增删改查的显示
用户名:
密码:
年龄:
id
用户名
年龄
var username = document.querySelector("#username")
var password = document.querySelector("#password")
var age = document.querySelector("#age")
var register = document.querySelector("#regi服务器托管网ster")
var update = document.querySelector("#update")
var remove = document.querySelector("#remove")
register.onclick = function () {
console.log(username.value, password.value, age.value)
fetch("/api/user/add", {
method: "POST",
body: JSON.stringify({
username: username.value,
password: password.value,
age: age.value
}),
headers: {
"Content-type": "application/json"
}
}).then(res => res.json()).then(res => {
console.log(res)
listUpdate()
})
}
update.onclick = function () {
console.log(username.value, password.value, age.value)
fetch("/api/user/update/653f7be831c2cf3a58098d25", {
method: "POST",
body: JSON.stringify({
username: username.value,
password: password.value,
age: "1"
}),
headers: {
"Content-type": "application/json"
}
}).then(res => res.json()).then(res => {
console.log(res)
listUpdate()
})
}
remove.onclick = function () {
console.log(username.value, password.value, age.value)
fetch("/api/user/delete/653f7be831c2cf3a58098d25").
then(res => res.json()).then(res => {
console.log(res)
listUpdate()
})
}
function listUpdate(){
fetch("/api/user/list").then(res => res.json()).then(res => {
console.log(res)
var tbody = document.querySelector("tbody")
tbody.innerHTML = res.map(item => `
${item._id}
${item.username}
${item.age}
`).join("")
})
}
listUpdate()
users.js
var express = require('express');
const UserModel = require('../model/UserModel');
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
router.post('/user/add', function (req, res, next) {
const { username, password, age } = req.body
UserModel.create({
username,
password,
age
}).then(data => {
console.log(data, "data is")
})
//插入数据库
res.send({
ok: 1
})
});
router.post('/user/update/:id', function (req, res, next) {
const { username, age, password } = req.body
UserModel.updateOne({ _id: req.params.id },{username}).then(data => {
res.send({
ok: 1
})
})
});
router.get('/user/delete/:id', function (req, res, next) {
const { username, age, password } = req.body
UserModel.deleteOne({ _id: req.params.id }).then(data => {
res.send({
ok: 1
})
})
});
router.ge服务器托管网t('/user/list', function (req, res, next) {
const { username, age, password }
= req.body
UserModel.find({},["username","age"]).sort({age:-1}).then(data=>{
res.send(data)
})
});
module.exports = router;
UserMode.js
const { Schema } = require("mongoose")
const mongoose=require("mongoose")
const UserType={
username:String,
password:String,
age:Number
}
const UserModel=mongoose.model("user",new Schema(UserType))
module.exports=UserModel
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
启动
npm run start
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
服务器托管,北京服务器托管,服务器租用,机房机柜带宽租用
咨询:董先生
电话13051898268 QQ/微信93663045!
上一篇: 前端学习笔记202310学习笔记第一百贰拾叁天-nodejs-业务分层7
下一篇: 前端学习笔记202310学习笔记第一百贰拾叁天-nodejs-业务分层6