下载mongoose
`npm install mongoose `
使用步骤
// 引入mongoose
const mongoose = require('mongoose')
// 连接数据库(如果不存在数据库 name在添加数据的时候会自动创建数据库)
mongoose.connect('mongodb://localhost/<databaseName>')
.then(()=>{
// coding
})
.catch(()=>{
// coding
})
// 创建规则
const userSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
......
})
// 使用规则创建集合
const User = mongoose.model('User',userSchema)
// 添加数据/文档
// 方法一:
// 创建User实例
const user = new User({
name: "JavaScript",
author: "Bucky",
isPublished: false
})
// 保存数据
user.save()
// 方法二:
User.create({
name: "JavaScript",
author: "Bucky",
isPublished: false
},(error,data)=>{
// 打印错误
console.log(err);
// 打印添加的数据
console.log(data);
})
// 方法三:
User.create({
name: "JavaScript",
author: "Bucky",
isPublished: false
})
.then(()=>{
// coding
})
.catch(()=>{
// coding
})
导入数据
mongoimport -d <数据库名字> -c <集合名字> --file <需要导入的数据路径>
数据查询
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,
password: String,
hobbies: [String]
})
// 此时的users里面已经存储着使用mongoimport导入的数据
const User = mongoose.model('User', userSchema)
// 查询全部数据
User.find().then((result)=>{console.log(result)})
// 查询 返回文档集合 数组里面的对象
User.find().then(result => { console.log(result); });
// 条件查询 返回的数组对象 查询id
User.find({ _id: '5c09f236aeb04b22f8460967' }).then(result => { console.log(result); });
// 返回一条数据 返回该条查询对象
User.findOne({ name: '王五' }).then(result => { console.log(result); });
// 返回年龄大于20 小于50 的对象 $gt : 大于 $lt : 小于
User.find({ age: { $gt: 20, $lt: 50 } }).then(result => { console.log(result); });
// 查询对象里面是数组的数据 包含 $in
User.find({ hobbies: { $in: ['足球'] } }).then(result => { console.log(result); });
// 选择要查询的字段 默认会显示id 只查询名字和年龄 -xxx 不显示该数据
User.find().select('name age -_id').then(result => { console.log(result); });
// 升序排序 按照年龄字段排序
User.find().sort('age').then(result => { console.log(result); });
// 降序排序 按照年龄字段排序
User.find().sort('-age').then(result => { console.log(result); });
// skip跳过多少条数据 limit限制查询的数量
User.find().skip(2).limit(3).then(result => { console.log(result); });
// 删除文档 查询一个并且删除该文档 返回删除的文档 {指定需要删除的对象条件}
User.findOneAndDelete({ name: '张三' }).then(result => { console.log(result); });
// 删除文档 查询并且删除多个文档 传入空对象会把里面的文档全部删除
User.deleteMany({}).then(result => { console.log(result); });
// { n:1 , ok: 1 } n代表删除的个数 ok 代表是否删除成功
// 更新 / 修改一个文档 返回的是对象 ({ 查询条件 }, { 要修改的值 })
User.updateOne({ name: "王二麻子" }, { name: "zs" }).then(result => { console.log(result); });
// { n: 1, nModified: 1, ok: 1 }
// n代表删除的个数 nModified 代表修改的个数 ok 代表是否删除成功
// 更新 / 修改多个文档
User.updatMany({ 查询条件 }, { 要修改的值 }).then(result=>{console.log(result);});
// 设置空对象 将所有的数据都修改后面设置的值
User.updatMany({}, { 要修改的值 }).then(result=>{console.log(result);});
验证规则
const validSchema = new mongoose.Schema({
title: {
// 类型
type: String,
// [设置验证,'错误信息提示']
// 必填项
required: [true, '必填项'],
// 字符串最小长度
minlength: [2, '最小长度是2'],
// 字符串最大长度
maxlength: [8, '最大长度是5'],
// 去除字符串首位空格
trim: true,
},
age: {
type: Number,
required: [true, '必填项'],
// 最小数字
min: 18,
// 最大数字
max: 100,
},
date: {
type: Date,
// 如果传入时间就使用 没传入就使用默认值
default: Date.now
},
// enum 枚举 列举出当前字段可以拥有的字段
category: {
type: String,
// 如果传递的category不在enum提供的字段里面 那么就会报错
enum: ['html', 'css', 'javascript', 'vue', 'node'],
},
author: {
type: String,
// 自定义验证器
validate: {
// valid 就是传入的author值
validator: (valid) => {
// 返回布尔值
return valid && valid.length > 4;
},
// 自定义错误信息
message: '输入的字段长度不符合要求'
}
}
});
集合关联
// 集合关联 不同集合的数据之间是有关联的
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
// 连接成功
.then(() => { console.log('数据库连接成功'); })
// 连接失败
.catch(err => {
console.log('err');
console.log('数据库连接失败');
})
const authorSchema = new mongoose.Schema({
name: {
type: String,
message: '作者名字错误',
required: true
}
})
const articalSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
author: {
// 集合关联(默认写法)
type: mongoose.Schema.Types.ObjectId,
// 与谁关联
ref: 'Author'
}
});
// 使用规则
const Author = mongoose.model('Author', authorSchema);
const Artical = mongoose.model('Artical', articalSchema);
// 添加数据
Author.create({ name: 'Taylor' }).then(res => { console.log(res); })
Artical.create({ title: 'Javascript', author: '60eaf9103d8b21ede8f546e6' }).then(res => { console.log(res); });
// 联合查询
Artical.find()
.populate('author')
.then((err, result) => {
console.log(err);
console.log(result);
})
- 插入的数据
-
author
-
articals
-
没有联合查询 author显示的内容
-
设置了联合查询 author显示的值
-