文章目录
数据库备份(有问题)
导出
mongodump -h 127.0.0.1 -d Blog -o C:\Users\Administrator\Desktop\data
导入
mongoimport --host=“dba/10.0.0.51:28017” -d Blog --dir C:\Users\tom\Desktop\data
创建数据库
connect.js
// 引入mongoose第三方模块
const mongoose = require('mongoose');
// 连接数据库logincs
let db="biquge_book"
mongoose.connect(`mongodb://localhost/${db}`, { useNewUrlParser: true ,useUnifiedTopology: true ,useCreateIndex:true})
.then(() => console.log(`数据库${db}连接成功`))
.catch(() => console.log(`数据库${db}连接失败`))
app.js
//连接数据库
require('./tool/connect');
创建对应的表
user.js
const mongoose = require('mongoose');
const Article=require("./article.js")
const Book=require("./book.js")
const userSchema = new mongoose.Schema({
//定义基本的表规则
//校验规则也可以自定义
money:{
min:0, //数字最小值
max:999999,
type:Number,
default:0,
require:[true,"金额"],
},
identity:{
type:String,
default:"tourist",
enum:["admin","teacher","student","tourist"] //表示必须是里面的一种,只能用在string
},
username: {
type: String,
maxlength: 20, //字符串长度
minlength: 2,
required: [true, "填写姓名2~20"],
unique:true, //表示这个属性不允许重复
trim:true, //自动去两侧的空格,lowercase,uppercase
match:/^admin(.*)/i //表示必须以admin开头,i 表示忽略大小写
},
password: {
type: String,
maxlength: 1000,
minlength: 4,
required: [true, '填写密码']
},
registerDate: {
type: Date,
default: Date.now //默认值
}
})
//不传第三个参数,默认操作users表,传入后,指定操作user表
// const User = mongoose.model('User', userSchema,"user");
// 创建集合,首字母必须是 大写的 User
//创建集合
const User = mongoose.model('User', userSchema);
crud
新增一个
async function add() {
var data1 = await new User({
username: " admin19 ",
password: "123456",
money:8
}).save() //必须要save()
console.log(data1)
}
删除
async function del() {
var data1 = await User.deleteOne({ //删除一个 deleteMany多个
username: "admin",
})
console.log(data1)
}
修改一个
//都支持回调的方式
function updataone() {
User.updateOne({
username: "admin",
}, {
username: "tom",
},
(err, data) => {
console.log(data)
}
)
}
修改多个
async function updatamany() {
let data=await User.updateMany({
password: "1232654",
}, {
password: "123456",
username:"tom"
},
)
}
查找满足条件的第一个
async function findone() {
let data=await User.findOne({
password: "123456",
})
console.log(data)
}
查找满足条件的全部并排序返回
//如果传入一个{} ,会查找全部
async function findmany() {
let data=await User.find({
password: "123456",
}).sort({chapter_pushtime:1}) //1 升序 ,-1 降序
console.log(data)
}
// add()
// del()
// updataone()
// updatamany()
// findone()
// findmany()
一些复杂的查询方式
//$equals 等于 / $gt 大于 / $gte 大于等于 / $lt 小余 / $lte 小余等于 / $ne 不等于 / $in 在数组中 / $nin 不在数组中
//条件查询
async function find(){
let data=await User.find({money: {$gt: 7,$lt:9}});
console.log(data)
}
分页查询
async function pagefind(){
num=1 //第几页
pageSize=5 //m每页多少条
skip=pageSize*(num-1) //跳过多少条,
let datalist=await User.find({}).skip(skip).limit(pageSize)
console.log(datalist)
}
返回总条数
async function count(){
let num=await User.find().countDocuments();
console.log(num)
}
返回指定字段
async function findTD(){
let datalist=await User.find({},{username:1}) //0表示不显示
console.log(datalist)
}
多表查询
async function someAfind(){
let datalist=await Article.find({article_name: "第4章标题"}).populate("author_id").populate("book_id").exec()
console.log(datalist)
}
扩展
// Person
// .find({ occupation: /host/ })
// .where(‘name.last’).equals(‘Ghost’) // Person.name.last是Ghost
// .where(‘age’).gt(17).lt(66) // 17 < Person.age <66
// .where(‘likes’).in([‘vaporizing’, ‘talking’])//likes是vaporizing或者talking
// .skip(10) //跳过前10条
// .limit(10) //限制10条记录
// .sort({time:-1}) //根据time的倒序排
// .select(‘name occupation’) //选择name和occupation字段
// .exec(callback);
模糊查询
//$regex 配置正则 只能查询string
async function mohu(){
let str="5f674a805eca9125a8944f32"
str=new RegExp(str,"i") //i 忽略大小写
let data=await User.find({
$or:[
{
id_:str //没有生效
},
{
username:{$regex:str}
}
]
})
console.log(data)
}
扩展
// Job.find({
// $or: [
// {'description': {'$regex': key, $options: '$i'}},
// {'city': {'$regex': key, $options: '$i'}},
// {'name': {'$regex': key, $options: '$i'}}]
// })
// .populate('JobType', 'name')
// .exec(function (err, jobs) {
// if (err) {
// callback(err);
// } else {
// callback(null, jobs);
// }
// })
// find()
// pagefind()
// count()
// findTD()
// someAfind()
// mohu()
module.exports=User
连表查询
article.js
// 引入mongoose第三方模块
const mongoose = require('mongoose');
const User=require("../app.js")
const Book=require("./book.js")
const articleSchema = new mongoose.Schema({
//作者id
author_id:{
type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
//book id
book_id:{
type:mongoose.Schema.Types.ObjectId,
ref:"Book"
},
//第几章节
article_number:{
min:0, //数字最小值
max:9999,
type:Number,
require:[true,"第几章节"],
},
//章节内容
article_doc:{
type: String,
maxlength: 100000, //字符串长度
minlength: 2,
required: [true, "章节内容"],
trim:true, //自动去两侧的空格,lowercase,uppercase
},
//章节名字
article_name: {
type: String,
maxlength: 20, //字符串长度
minlength: 2,
required: [true, "章节名字"],
unique:true, //表示这个属性不允许重复
trim:true, //自动去两侧的空格,lowercase,uppercase
},
//默认创建时间
registerDate: {
type: Date,
default: Date.now //默认值
}
})
// 创建集合,首字母必须是 大写的 User
const Article = mongoose.model('Article', articleSchema);
新增一个
async function add1() {
var data1 = await new Article({
author_id:"5f6746e559d30800f0048c59",
book_id:"5f675a214c484f21a45c729d",
article_name: "第4章标题",
article_number: 2,
article_doc:"第2章内容"
}).save()
console.log(data1)
}
查找
async function find() {
let data=await Article.find({})
console.log(data)
}
// find()
// add1()
module.exports=Article
book.js
// 引入mongoose第三方模块
const mongoose = require('mongoose');
const bookSchema = new mongoose.Schema({
//作者id
aid:{
type:mongoose.Schema.Types.ObjectId
},
//作者
book_author:{
type: String,
maxlength: 10, //字符串长度
minlength: 2,
required: [true, "作者"],
trim:true, //自动去两侧的空格,lowercase,uppercase
},
//书名字
book_name: {
type: String,
maxlength: 20, //字符串长度
minlength: 2,
required: [true, "书名字"],
unique:true, //表示这个属性不允许重复
trim:true, //自动去两侧的空格,lowercase,uppercase
},
//默认创建时间
registerDate: {
type: Date,
default: Date.now //默认值
}
})
// 创建集合,首字母必须是 大写的 User
const Book = mongoose.model('Book', bookSchema);
//新增一个
async function add1() {
var data1 = await new Book({
book_author: "admin",
book_name: "第3本书名",
}).save()
console.log(data1)
}
// add1()
module.exports=Book
特殊查询示例
查找一个时间段的数据
let data = await ApiText.find({ api_create_time: { $gt: start,$lt: end}})
模糊查询示例
表字段:
const UserSchema = new mongoose.Schema(
{
arr:[
"xiaowang",
"xiaoli",
"china"
]
}
)
查询字段
User.find({arr:"xiaowang"})