Mongoose第三方包:
使用Node.js操作MongoDB數(shù)據(jù)庫需要依賴Node.js第三方包mongoose
使用npm install mongoose命令下載
啟動MongoDB
在命令行工具中運行net start mongoDB即可啟動MongoDB,否則MongoDB將無法連接。
數(shù)據(jù)庫連接:
使用mongoose提供的connect方法即可連接數(shù)據(jù)庫
// 引入mongoose第三方模塊 用來操作數(shù)據(jù)庫
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', {
useNewUrlParser: true,
useUnifiedTopology: true //這個即是報的警告
})
// 連接成功
.then(() => console.log('數(shù)據(jù)庫連接成功'))
// 連接失敗
.catch(err => console.log(err, '數(shù)據(jù)庫連接失敗'));
創(chuàng)建集合與文檔:
創(chuàng)建集合分為兩步,一是對對集合設(shè)定規(guī)則,二是創(chuàng)建集合,創(chuàng)建mongoose.Schema構(gòu)造函數(shù)的實例即可創(chuàng)建集合。
創(chuàng)建文檔實際上就是向集合中插入數(shù)據(jù)。
分為兩步:
1.創(chuàng)建集合實例。
2.調(diào)用實例對象下的save方法將數(shù)據(jù)保存到數(shù)據(jù)庫中。
// 引入mongoose第三方模塊 用來操作數(shù)據(jù)庫
const mongoose = require('mongoose');
// 數(shù)據(jù)庫連接
mongoose.connect('mongodb://localhost/playground', { 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: '數(shù)據(jù)可視化',
author: '你管我是誰',
isPublished: true
});
// 將文檔插入到數(shù)據(jù)庫中
course.save();
向集合中插入文檔的另一種方式
// 向集合中插入文檔
Course.create({name: 'Javascript', author: '啊啊啊', isPublished: false}, (err, result) => {
console.log(err)
console.log(result)
})
// 方式2
Course.create({name: 'Javascript123', author: 'aa', isPublished: false})
.then(result => {
console.log(result)
})
mongoDB數(shù)據(jù)庫導(dǎo)入數(shù)據(jù):
mongoimport -d playground -c users --file user.json
根據(jù)條件查詢文檔
//查詢用戶集合中的所有文檔
User.find().then(result => console.log(result));
//通過_id字段查找文檔
User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
//findOne方法返回一條文檔 默認(rèn)返回當(dāng)前集合中的第一條文檔
User.findOne({name: '李四'}).then(result => console.log(result))
//查詢用戶集合中年齡字段大于20并且小于40的文檔
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))
//查詢用戶集合中hobbies字段值包含足球的文檔 $in
User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
//選擇要查詢的字段
User.find().select('name email -_id').then(result => console.log(result))
//根據(jù)年齡字段進(jìn)行升序排列
User.find().sort('age').then(result => console.log(result))
//根據(jù)年齡字段進(jìn)行降序排列
User.find().sort('-age').then(result => console.log(result))
//查詢文檔跳過前兩條結(jié)果 限制顯示3條結(jié)果
User.find().skip(2).limit(3).then(result => console.log(result))
刪除文檔:
// 查找到一條文檔并且刪除
// 返回刪除的文檔
// 如何查詢條件匹配了多個文檔 那么將會刪除第一個匹配的文檔
User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// 刪除多條文檔
User.deleteMany({}).then(result => console.log(result))
更新文檔:
// 更新單個
User.updateOne({查詢條件}, {要修改的值}).then(result => console.log(result))
// 更新多個
User.updateMany({查詢條件}, {要更改的值}).then(result => console.log(result))
mongoose驗證:
- 在創(chuàng)建集合規(guī)則時,可以設(shè)置當(dāng)前字段的驗證規(guī)則,驗證失敗就則輸入插入失敗。
required: true 必傳字段
minlength:3 字符串最小長度
maxlength: 20 字符串最大長度
min: 2 數(shù)值最小為2
max: 100 數(shù)值最大為100
enum: ['html', 'css', 'javascript', 'node.js']
trim: true 去除字符串兩邊的空格
validate: 自定義驗證器
default: 默認(rèn)值 - 獲取錯誤信息:error.errors['字段名稱'].message
集合關(guān)聯(lián)實現(xiàn)
通常不同集合的數(shù)據(jù)之間是有關(guān)系的,例如文章信息和用戶信息存儲在不同集合中,但文章是某個用戶發(fā)表的,要查詢文章的所有信息包括發(fā)表用戶,就需要用到集合關(guān)聯(lián)。
- 使用id對集合進(jìn)行關(guān)聯(lián)
-
使用populate方法進(jìn)行關(guān)聯(lián)集合查詢
image.png
// 用戶集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } }));
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
title: { type: String },
// 使用ID將文章集合和作者集合進(jìn)行關(guān)聯(lián)
author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//聯(lián)合查詢
Post.find()
.populate('author')
.then((err, result) => console.log(result));
