目录
一、Mongodb插入数据
//连接数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{useNewUrlParser:true,useUnifiedTopology: true})
.then(()=>console.log('数据库连接成功'))
.catch((err)=>console.log(err,'数据库连接失败'))
//创建规则集合
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) //coures
//第一种数据插入方式
/*const course = new Course({
name:'Nodejs学习',
author:'CXC',
isPublished: true
})
course.save();*/
//第二种数据插入方式
Course.create({name:'前端学习', author: 'cxc', isPublished: false},(err,result)=>{
console.log(err);
console.log(result)
})
Course.create({name:'前端学习1', author: 'cxc', isPublished: false})
.then(result=>console.log(result))
.catch(err=>console.log(err))
MongoDB Compass 内显示已成功插入数据
二、Mongodb导入数据
- 找到MongoDB安装文件夹下的mongoimport 文件;
- D:\Program Files\MongoDB\Server\4.2\bin ;
- 在系统环境变量path中添加该路径;
- 使用mongoimport –d 数据库名称 –c 集合名称 --file 要导入的文件位置以及名称;
5.导入成功
三、
Mongodb数据库查询文档
.find({}) 返回数组形式,返回一组文档
.findOne({}) 返回一条文档 默认返回当前集合中第一条文档
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:/playground',{useNewUrlParser: true,useUnifiedTopology: true})
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log(err,'数据库连接失败'))
const userSchema = new mongoose.Schema({
name:String,
age:Number,
email:String,
hobbies:[String]
})
const User = mongoose.model('User',userSchema)
//查询用户集合中的所有文档
//User.find().then(result=>console.log(result))
User.find({_id: '5c09f236aeb04b22f8460967'}).then(result=>console.log(result))
//默认返回当前集合中第一条文档
//User.finOne().then(result=>console.log(result));
User.findOne({_id: '5c09f236aeb04b22f8460967'}).then(result=>console.log(result));
四、
Mongodb数据库删除文档
const User = mongoose.model('User',userSchema);
//删除单个 如果有多个,则删除第一个匹配项
User.findOneAndDelete({hobbies:'打豆豆'}).then((result)=>console.log(result))
//删除多个
User.deleteMany().then((result)=>console.log(result))
五、
Mongodb数据库更新文档
const User = mongoose.model('User',userSchema);
//更新单个 如果有多个,则更新第一个匹配项
User.updateOne({name:'狗蛋'},{name:'狗剩'})
.then((result)=>console.log(result))
//更新多个
User.updateMany({},{name:'陈六'})
.then((result)=>console.log(result))
六、集合关联
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
- 使用id对集合进行关联;
- 使用populate方法进行关联集合查询。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:/playground', { useNewUrlParser: true,useUnifiedTopology: true })
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log(err,'数据库连接失败'))
const userSchema = new mongoose.Schema({
name: {
type:String,
required:true
},
age:Number
})
const postSchema = new mongoose.Schema({
title:String,
author:{
type:mongoose.SchemaTypes.ObjectId,
ref:'User1' //绑定User1
}
})
const User = mongoose.model('User1',userSchema);
const Post = mongoose.model('Post1',postSchema);
User.create({name:'cxc',age:18}).then(result=>console.log(result));
Post.create({title:'nodejs',author: '5ebc05d390cb9304b424aa00'}).then(result=>console.log(result))
Post.find().populate('author').then(result=>console.log(result)) //通过关联查询出用户姓名、年龄
七、实例
/* 未使用模板引擎 1. 搭建网站服务器,实现客户端与服务端的通信; 2. 连接数据库,创建用户集合,向集合中插入文档; 3. 当用户访问/list时,将所有用户信息查询出来; //实现路由功能 //呈现用户列表界面 //从数据库中查询用户信息 将用户信息展示在列表中 4. 将用户信息和表格HTML进行拼接并将结果响应回客户端; 5. 当用户访问/add时,呈现表单界面,并实现添加用户信息功能; 6. 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能; //增加页面路由 呈现页面 //在点击修改按钮的时候,将用户ID传递到当前页面 //从数据库中查询当前用户信息,将用户信息展示到页面中 //实现用户修改功能 //指定表单的提交地址以及请求方式 //接收客户端传递过来的用户信息 找到用户 将用户更新 7. 当用户访问/delete时,实现用户删除功能。 */ const http = require('http'); const app = http.createServer(); const url = require('url'); const queryString = require('querystring'); require('./model/index'); const User = require('./model/user'); app.on('request',async (req,res)=>{ const method = req.method; const {pathname,query} = url.parse(req.url,true); if(method == 'GET') { if (pathname == '/list') { let users = await User.find(); let list = `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户列表</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"> </head> <body> <div class="container"> <h6> <a href="/add" class="btn btn-primary">添加用户</a> </h6> <table class="table table-striped table-bordered"> <tr> <td>用户名</td> <td>年龄</td> <td>爱好</td> <td>邮箱</td> <td>操作</td> </tr> ` users.forEach(item => { list += `<tr> <td>${item.name}</td> <td>${item.age}</td> <td>` item.hobbies.forEach(item => { list += `<span>${item} </span>` }) list += ` <td>${item.email}</td> <td> <a href="/delete?id=${item._id}" class="btn btn-danger btn-xs">删除</a> <a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a> </td>` }) list += ` </tr> </table> </div> </body> </html>` res.end(list); } else if (pathname == '/add') { let add = `<!DOCTYPE html>; <html lang="en"> <head> \t<meta charset="UTF-8"> \t<title>用户列表</title> \t<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3>添加用户</h3> <form method="post" action="/add"> <div class="form-group"> <label>用户名</label> <input name="name" type="text" class="form-control" placeholder="请填写用户名"> </div> <div class="form-group"> <label>密码</label> <input name="password" type="password" class="form-control" placeholder="请输入密码"> </div> <div class="form-group"> <label>年龄</label> <input name="age" type="text" class="form-control" placeholder="请填写邮箱"> </div> <div class="form-group"> <label>邮箱</label> <input name="email" type="email" class="form-control" placeholder="请填写邮箱"> </div> <div class="form-group"> <label>请选择爱好</label> <div> <label class="checkbox-inline"> <input type="checkbox" value="足球" name="hobbies"> 足球 </label> <label class="checkbox-inline"> <input type="checkbox" value="篮球" name="hobbies"> 篮球 </label> <label class="checkbox-inline"> <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球 </label> <label class="checkbox-inline"> <input type="checkbox" value="敲代码" name="hobbies"> 敲代码 </label> <label class="checkbox-inline"> <input type="checkbox" value="抽烟" name="hobbies"> 抽烟 </label> <label class="checkbox-inline"> <input type="checkbox" value="喝酒" name="hobbies"> 喝酒 </label> <label class="checkbox-inline"> <input type="checkbox" value="烫头" name="hobbies"> 烫头 </label> </div> </div> <button type="submit" class="btn btn-primary">添加用户</button> </form> </div> </body> </html>`; res.end(add); } else if (pathname == '/modify') { let user = await User.findOne({_id: query.id}); let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '烫头']; let modify = `<!DOCTYPE html> <html lang="en"> <head> \t<meta charset="UTF-8"> \t<title>用户列表</title> \t<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3>修改用户</h3> <form method="post" action="/modify?id=${user._id}"> <div class="form-group"> <label>用户名</label> <input value="${user.name}" name="name" type="text" class="form-control" placeholder="请填写用户名"> </div> <div class="form-group"> <label>密码</label> <input value="${user.password}" name="password" type="password" class="form-control" placeholder="请输入密码"> </div> <div class="form-group"> <label>年龄</label> <input value="${user.age}" name="age" type="text" class="form-control" placeholder="请填写邮箱"> </div> <div class="form-group"> <label>邮箱</label> <input value="${user.email}" name="email" type="email" class="form-control" placeholder="请填写邮箱"> </div> <div class="form-group"> <label>请选择爱好</label> <div> `; hobbies.forEach(item => { if (user.hobbies.includes(item)) { modify += `<label class="checkbox-inline"> <input type="checkbox" value="${item}" name="hobbies" checked> ${item} </label>` } else { modify += `<label class="checkbox-inline"> <input type="checkbox" value="${item}" name="hobbies" > ${item} </label>` } }) modify += ` </div> </div> <button type="submit" class="btn btn-primary">修改用户</button> </form> </div> </body> </html>`; res.end(modify); } else if (pathname == '/delete') { await User.findOneAndDelete({_id: query.id}); res.writeHead(301,{ Location:'/list' }) res.end(); } } else if (method == 'POST') { if (pathname == '/add') { let formData = ''; req.on('data', param => { formData += param; }); req.on('end', async () => { let user = queryString.parse(formData); await User.create(user); res.writeHead(301, { Location: '/list' }) res.end(); }); } else if (pathname == '/modify') { let formData = ''; req.on('data', param => { formData += param; }); req.on('end', async () => { let user = queryString.parse(formData); await User.updateOne({_id: query.id}, user); res.writeHead(301, { Location: '/list' }) res.end(); }); } } }) app.listen(3000); console.log('服务器部署成功')