一、下載Node的數(shù)據(jù)庫三方包(mongoose)
npm install mongoose
//引入三方包
const mongoose = require('mongoose')
//連接數(shù)據(jù)庫
mongoose.connect('mongodb://localhost/day01', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('數(shù)據(jù)庫連接成功'))
.catch(err => console.log(err, '數(shù)據(jù)庫連接失敗'))
// 創(chuàng)建集合規(guī)則
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
});
// 使用規(guī)則創(chuàng)建集合
// 1.集合名稱
// 2.集合規(guī)則
const Course = mongoose.model('Course', courseSchema) // courses
//第一種方式
// 創(chuàng)建文檔
const course = new Course({
name: 'node.js基礎(chǔ)',
author: '張三',
isPublished: true
});
// 將文檔插入到數(shù)據(jù)庫中
course.save();
//第二種方式
Course.create({name: 'Javascript123', author: '黑馬講師', isPublished: false})
.then(result => {
console.log(result)
})
二、查詢
// 創(chuàng)建集合規(guī)則
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
// 使用規(guī)則創(chuàng)建集合
const User = mongoose.model('User', userSchema);
// 查詢用戶集合中的所有文檔
// User.find().then(result => console.log(result));
// 通過_id字段查找文檔
// User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// findOne方法返回一條文檔 默認返回當前集合中的第一條文檔
User.findOne({name: '李四'}).then(result => console.log(result))
// 查詢用戶集合中年齡字段大于20并且小于40的文檔
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))
// 查詢用戶集合中hobbies字段值包含足球的文檔
User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
// 選擇要查詢的字段
User.find().select('name email -_id').then(result => console.log(result))
// 根據(jù)年齡字段進行升序排列
User.find().sort('age').then(result => console.log(result))
// 根據(jù)年齡字段進行降序排列
User.find().sort('-age').then(result => console.log(result))
// 查詢文檔跳過前兩條結(jié)果 限制顯示3條結(jié)果
User.find().skip(2).limit(3).then(result => console.log(result))
三、刪除
// 創(chuàng)建集合規(guī)則
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
// 使用規(guī)則創(chuàng)建集合
const User = mongoose.model('User', userSchema);
// 查找到一條文檔并且刪除
// 返回刪除的文檔
// 如何查詢條件匹配了多個文檔 那么將會刪除第一個匹配的文檔
User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// 刪除多條文檔
User.deleteMany({}).then(result => console.log(result))
四、修改
// 創(chuàng)建集合規(guī)則
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
password: String,
hobbies: [String]
});
// 使用規(guī)則創(chuàng)建集合
const User = mongoose.model('User', userSchema);
// 找到要刪除的文檔并且刪除
// 返回是否刪除成功的對象
// 如果匹配了多條文檔, 只會刪除匹配成功的第一條文檔
User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))
// 找到要刪除的文檔并且刪除
User.updateMany({}, {age: 300}).then(result => console.log(result))
五、校驗字段
const postSchema = new mongoose.Schema({
title: {
type: String,
// 必選字段
required: [true, '請傳入文章標題'],
// 字符串的最小長度
minlength: [2, '文章長度不能小于2'],
// 字符串的最大長度
maxlength: [5, '文章長度最大不能超過5'],
// 去除字符串兩邊的空格
trim: true
},
age: {
type: Number,
// 數(shù)字的最小范圍
min: 18,
// 數(shù)字的最大范圍
max: 100
},
publishDate: {
type: Date,
// 默認值
default: Date.now
},
category: {
type: String,
// 枚舉 列舉出當前字段可以擁有的值
enum: {
values: ['html', 'css', 'javascript', 'node.js'],
message: '分類名稱要在一定的范圍內(nèi)才可以'
}
},
author: {
type: String,
validate: {
validator: v => {
// 返回布爾值
// true 驗證成功
// false 驗證失敗
// v 要驗證的值
return v && v.length > 4
},
// 自定義錯誤信息
message: '傳入的值不符合驗證規(guī)則'
}
}
});
const Post = mongoose.model('Post', postSchema);
Post.create({title:'aa', age: 60, category: 'java', author: 'bd'})
.then(result => console.log(result))
.catch(error => {
// 獲取錯誤信息對象
const err = error.errors;
// 循環(huán)錯誤信息對象
for (var attr in err) {
// 將錯誤信息打印到控制臺中
console.log(err[attr]['message']);
}
})
六、連表查詢
// 用戶集合規(guī)則
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
// 文章集合規(guī)則
const postSchema = new mongoose.Schema({
title: {
type: String
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
// 用戶集合
const User = mongoose.model('User', userSchema);
// 文章集合
const Post = mongoose.model('Post', postSchema);
// 創(chuàng)建用戶
User.create({name: 'itheima'}).then(result => console.log(result));
// 創(chuàng)建文章
Post.create({titile: '123', author: '5c0caae2c4e4081c28439791'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result))