mongodb之 mongodb 入门教程
下载方式: ww.mongodb.com/download-center/community(自动识别使用系统下载)
node.js中使用需要下载:npm install mongoose(命令)
01:连接数据库
const mongoose = require('mongoose');
mongodb: //[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('数据库已链接!'))
.catch(err => console.log('数据库链接失败!'))
02:创建集合
//1,创建集合的规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
})
// 2, 使用规则创建集合 参数1:集合名称(对应数据库中的集合) 参数2:集合对象
const Course = mongoose.model('Course', courseSchema) //course
// 创建集合实例
const course = new Course({
name: 'js基础',
author: '小程',
isPublished: true
});
//将文档插入数据库
course.save();
03:创建集合的第二种方法
//创建用户集合
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 20
},
age: {
type: Number,
min: 18,
max: 80
},
password: {
type: String
},
email: String,
hobbies: [String]
})
// 2, 创建集合返回集合构造函数
const Course = mongoose.model('User', UserSchema);
//返回的是promise对象形式
Course.create({ name: '小明', age: 18, password: '123456', email: '2607258553@qq.com', hobbies: ['吃饭', '睡觉', '打豆豆'] })
.then(result => console.log(result))
.catch(err => console.log(err))
04:查询文档
//1,创建集合的规则
const userSchema = new mongoose.Schema({
id: Number,
name: String,
author: String,
isPublished: Boolean,
material: [String]
})
// 2, 使用规则创建集合 参数1:集合名称 参数2:集合对象
const User = mongoose.model('Course', userSchema) //userSchema
//查询用户集合中的所有文档
// User.find().then(result => console.log(result))
//根据条件进行查询
// User.find({ _id: '5f7fceca8c6c503ea850cd9b' }).then(result => console.log(result));
//只查询一条 只返回当前集合中的第一条 类型为对象
// User.findOne().then(result => console.log(result))
// User.findOne({ id: 3 }).then(result => console.log(result));
// User.find({ id: { $gt: 2, $lt: 5 } }).then(result => console.log(result));
// User.find({ material: { $in: ['菠萝'] } }).then(result => console.log(result));
// 选择要查询的字段
// User.find().select('id name').then(result => console.log(result))
// 顺序排列 不加负号从小到大,加了负号从大到小
// User.find().sort('-id').then(result => console.log(result))
// skip跳过多少条数据 limit限制查询的数量
// User.find().skip(2).limit(3).then(result => console.log(result))
05:删除文档
//1,创建集合的规则
const userSchema = new mongoose.Schema({
id: Number,
name: String,
author: String,
isPublished: Boolean,
material: [String]
})
// 2, 使用规则创建集合 参数1:集合名称 参数2:集合对象
const Course = mongoose.model('Course', userSchema) //userSchema
//删除单个文件 返回值是删除的文档
// Course.findOneAndDelete({ id: 1 }).then(result => console.log(result));
// 删除多个
Course.deleteMany({}).then(result => console.log(result));
06:更改文档信息
//1,创建集合的规则
const userSchema = new mongoose.Schema({
id: Number,
name: String,
author: String,
isPublished: Boolean,
material: [String]
})
// 2, 使用规则创建集合 参数1:集合名称 参数2:集合对象
const Course = mongoose.model('Course', userSchema) //userSchema
//更新单个文档操作 第一个参数查询条件,第二个参数更改的值
// Course.updateOne({ id: 1 }, { name: 'Python' }).then(result => console.log(result));
Course.updateMany({}, { author: '程老师' }).then(result => console.log(result));
07:mongoose验证
//1,创建集合的规则
const courseSchema = new mongoose.Schema({
id: {
type: Number,
// required: true
required: [true, '索引ID不能为空哦!'],
max: [20, '索引不能大于2'],
trim: true
},
name: {
type: [String],
// required: true
required: [true, '名称不能为空哦'],
maxlength: [5, '课程名长度不能大于2'],
trim: true
},
author: {
type: String,
validate: {
validator: v => {
//返回布尔值,
//true验证成功
//false验证 失败
//v要验证的值
return v && v.length > 4
},
message: '作者名的长度应该大于4'
}
},
isPublished: Boolean,
material: {
type: String,
enum: {
values: ['橘子', '菠萝'],
message: '种类必须是存在数组中的数据'
}
},
publishDate: {
type: Date,
//default代表默认值
default: Date
}
})
// 2, 使用规则创建集合 参数1:集合名称 参数2:集合对象
const Course = mongoose.model('Course', courseSchema) //course
Course.create({ id: 8, name: 'php', author: '波啊', isPublished: false, material: '榴莲' })
.then(result => console.log(result))
.catch(error => {
const err = error.errors;
for (var attr in err) {
// 错误信息打印到控制台
console.log(err[attr]['message']);
}
})
08:集合关联实现
//用户集合规则
const userSchema = new mongoose.Schema({
name: {
type: String,
require: true
}
});
//文章集合规则
const postSchema = new mongoose.Schema({
title: {
type: String
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
// 2, 使用规则创建集合 参数1:集合名称 参数2:集合对象
const User = mongoose.model('User', userSchema) //userSchema
const Post = mongoose.model('Post', postSchema) //userSchema
//创建用户
// User.create({ name: 'chengxinwen' }).then(result => console.log(result));
// Post.create({ title: '123', author: '5f800e1dba60ad07b8fa8b74' }).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result));
小试牛刀
user文件:
![](https://img.haomeiwen.com/i24893286/67b40c59444a5187.png)
index.js文件
![](https://img.haomeiwen.com/i24893286/0e52629590b34908.png)
//搭建服务器,实现客户端与服务器的通信
//链接数据库,创建用户集合,向集合中插入文档
//当用户访问/list时,将所有用户信息查询出来
//将用户信息和表格html进行拼接并将拼接结果响应给客户端
//当用户访问/aa时,呈现表单页面,并实现添加用户信息功能
//当用户访问/modify时,呈现修改页面,实现用户修改功能
//用户访问delet时候,实现用户删除功能
const http = require('http');
const url = require('url');
const querystring = require('querystring');
// 27017是mongdb数据库的默认端口
require('./model/index')
const User = require('./model/user')
//创建服务器
const app = http.createServer();
//为服务器对象添加请求事件
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();
//html字符串
let list = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格列表</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.container {
margin: 0 auto;
}
td {
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2>
<a class="btn btn-primary" href="./add">添加用户</a>
</h2>
<table class="table table-bordered table-striped table-hover">
<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>
<td>
<a class="btn btn-primary" href="./modify?id=${item.id}">修改</a>
<a class="btn btn-danger" href="./delete?id=${item.id}">删除</a>
</td>
</tr>
`
})
list += `
</table>
</div>
</body>
</html>
`
res.end(list)
} else if (pathname == '/add') {
let add = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>新增列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.container {
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<form action="/add" method="post">
<div class="form-group">
<label for="exampleInputName">用户名</label>
<input type="text" name='name' class="form-control" id="exampleInputName" placeholder="username">
</div>
<div class="form-group">
<label for="exampleInputEmail">邮箱</label>
<input type="email" name='email' class="form-control" id="exampleInputEmail" placeholder="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码</label>
<input type="password" name='password' class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputAge">年龄</label>
<input type="age" name='age' class="form-control" id="exampleInputAge" placeholder="age">
</div>
<div class="checkbox">
<label>
<input name='hobbies' value="足球" type="checkbox">足球
</label>
<label>
<input name='hobbies' value="抽烟" type="checkbox">抽烟
</label>
<label>
<input name='hobbies' value="打架" type="checkbox">打架
</label>
<label>
<input name='hobbies' value="喝酒" type="checkbox">喝酒
</label>
<label>
<input name='hobbies' value="烫头" type="checkbox">烫头
</label>
<label>
<input name='hobbies' value="写代码" type="checkbox">写代码
</label>
</div>
<button type="submit" class="btn btn-primary">添加用户</button>
</form>
</div>
</body>
</html>`;
res.end(add);
} else if (pathname == '/modify') {
//根据id查询数据
let userInfo = await User.findOne({ _id: query.id });
let hobbies = ['足球', '抽烟', '打架', '喝酒', '烫头', '写代码']
let update = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>修改页面</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.container {
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<form action="/add" method="post">
<div class="form-group">
<label for="exampleInputName">用户名</label>
<input type="text" value='${userInfo.name}' name='name' class="form-control" id="exampleInputName" placeholder="username">
</div>
<div class="form-group">
<label for="exampleInputEmail">邮箱</label>
<input type="email" value='${userInfo.email}' name='email' class="form-control" id="exampleInputEmail" placeholder="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码</label>
<input type="password" value='${userInfo.password}' name='password' class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputAge">年龄</label>
<input type="age" value='${userInfo.age}' name='age' class="form-control" id="exampleInputAge" placeholder="age">
</div>
<div class="checkbox">`
hobbies.forEach(item => {
//判断当前循环在不在用户爱好中
// console.log(userInfo.hobbies.includes(item));
let ishobby = userInfo.hobbies.includes(item)
if (ishobby) {
update += `
<label>
<input name='hobbies' value="${item}" checked type="checkbox">${item}
</label> `
} else {
update += `
<label>
<input name='hobbies' value="${item}" type="checkbox">${item}
</label> `
}
})
update += `
</div>
<button type="submit" class="btn btn-primary">修改用户</button>
</form>
</div>
</body>
</html>`;
res.end(update);
} else if (pathname == '/delete') {
//获取传过来的id
let deletId = query.id;
//将用户提交的信息添加到数据库
await User.findOneAndDelete({ _id: deletId });
//301代表重定向, location跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
}
} else if (method == 'POST') {
//用户添加功能
if (pathname == '/add') {
//接收用户提交的信息
let formData = '';
//接收post参数
req.on('data', param => {
formData += param;
})
//post参数接收完毕
req.on('data', async() => {
let user = querystring.parse(formData);
//将用户提交的信息添加到数据库
await User.create(user);
//301代表重定向, location跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
})
} else if (pathname = '/modify') {
//用户添加功能
if (pathname == '/add') {
//接收用户提交的信息
let formData = '';
//接收post参数
req.on('data', param => {
formData += param;
})
//post参数接收完毕
req.on('data', async() => {
let user = querystring.parse(formData);
//将用户提交的信息添加到数据库
await User.updateOne(user);
//301代表重定向, location跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
})
}
}
}
})
//监听端口
app.listen(3000)
网友评论