连接数据库
mongoose.connect(url, options).then().catch()
创建集合规则
const collection = new mongoose.Schema({
name: String,
age: Number
})
使用规则创建集合
// users
const User = mongoose.model('User', collection)
创建数据
const user = new User({
name: 'Tom',
age: 32
})
保存
user.save()
// 向集合中插入文档
User.create({ name: 'TOM', age: 22 }, (err, docs) => {})
User.create({ name: 'TOM', age: 22 }).then().catch()
//mongodb数据库导入数据
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件
// $in 包含
User.find({ address: {$in: ['四川']} }).then()
// 查询的字段 -字段名(不想查询的字段)
User.find().select('name age -address').then()
// sort: 排序 sort('age') 升序排序 sort('-age') 降序
// 删除单个,返回删除的数据
User.findOneAndDelete({}).then(res)
// 删除多个
User.deleteMany({})
// 更新单个
User.updateOne({查询条件}, {修改条件}).then()
// 更新多个
User.updateMany({查询条件}, {修改条件}).then()
验证
const user = new User({
name: {
type: String,
required: [true, '请输入姓名'],
minlength: [2, 姓名长度不能小于2],
maxlength: 5,
trim: true // 去掉空格
},
age: {
type: Number,
min: 10,
max: 88
},
date: {
type: Date,
default: Date.now // 默认值
},
category: {
type: String,
// 当前字段可拥有的值
enum: ['Java', 'Html', 'Vue', 'React'],
// 或者
enum: {
values: ['Vue', 'React'],
message: '字段值不符合规则'
}
},
author: {
type: String,
validate: {
// 自定义验证
validator: value => {
return value && value.length > 4
},
message: '格式不正确'
}
}
})
// 集合关联
const User = mongoose.model('User', new mongoose.Schema({
name: {
type: String
}
}))
const Post = mongoose.model('Post', new mongoose.Schema({
title: { type: String },
author: {
// id将文章集合与用户集合进行关联
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}))
// 联合查询
Post.find().populate('author').then().catch()