Mongoose是什么?
Mongoose是MongoDB的一個對象模型工具,封裝了許多MongoDB對文檔的的增刪改查等常用方法,讓NodeJS操作Mongodb數(shù)據(jù)庫變得更加靈活簡單。
在egg項目中如何使用?
1、安裝
npm i egg-mongoose --save
2、配置
在根目錄下的/config/plugin.js中配置插件
exports.mongoose = { enable: true, package: 'egg-mongoose',};
3、連接數(shù)據(jù)庫
在根目錄下的/config/config.default.js增加配置,其中url為我們的數(shù)據(jù)庫地址,可通過環(huán)境變量來區(qū)分開發(fā)環(huán)境還是生產(chǎn)環(huán)境,并且確定是否使用用戶名密碼的數(shù)據(jù)庫const prod = process.env.npm_config_server_prod;
mongoose: { client: { url: prod ? 'mongodb:eggadmin:123456@localhost:27017/DbName' : 'mongodb://127.0.0.1:27017/DbName', options: { useUnifiedTopology: true, }, }, },
4、配置與使用
(1)數(shù)據(jù)表配置
在app目錄下新建model文件夾,在model文件夾下新建JS文件作為數(shù)據(jù)表的配置內(nèi)容,下面以書籍表的配置為例
'use strict';/** * @description: Mongoose book Schema, */module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const BookSchema = new Schema({ desc: { type: String }, /* 書籍描述 */ name: { type: String }, /* 書籍名稱 */ press: { type: String }, /* 出版社 */ author: { type: String }, /* 作者 */ image: { type: Array }, /* 書籍圖片列表*/ price: { type: String }, /* 價格 */ book_type: { /* 書籍分類id */ type: Schema.Types.ObjectId, ref: 'BookClassify', }, user: { /* 書籍發(fā)布者id */ type: Schema.Types.ObjectId, ref: 'User', }, create_time: { type: String }, /* 創(chuàng)建時間 */ status: { type: String }, /* 狀態(tài),1:待購買,2:已購買*/ look: { type: Number } /* 瀏覽數(shù)量 */ }); return mongoose.model('Book', BookSchema);};
可以看到我們可以通過Schema來定義表結(jié)構(gòu),可以指定字段的類型及關(guān)聯(lián),設(shè)置完字段后就可以生成model了,這里算是非常簡單的配置,更多配置方法可參考文檔
(2)、使用mongoose方法
配置完數(shù)據(jù)表結(jié)構(gòu)后,我們就可以再service層中調(diào)用mongoose的方法對文檔進行增刪查改了,已書籍列表的處理邏輯為例子
async findbookList(data) { const { type, page, pageSize, desc, status, userId } = data; const searchVal = {} if (type) { searchVal.book_type = mongoose.Types.ObjectId(type) } if (status) { searchVal.status = status } if (userId) { searchVal.user = mongoose.Types.ObjectId(userId) } const search_term = { $or: [ { desc: { $regex: desc ? desc : '', $options: '$i' } }, { name: { $regex: desc ? desc : '', $options: '$i' } }, { author: { $regex: desc ? desc : '', $options: '$i' } }, { press: { $regex: desc ? desc : '', $options: '$i' } }, ], }; const totalNum = await this.ctx.model.Book.find(searchVal).and(search_term).countDocuments(); const result = await this.ctx.model.Book.find(searchVal) .populate({ path: 'user', select: { name: 1, image: 1 } }) .populate({ path: 'book_type' }) .and(search_term) .sort({ create_time: -1 }) .skip((parseInt(page) - 1) * parseInt(pageSize)) .limit(parseInt(pageSize)); return result ? { bean: { records: result, current: page, size: result.length, total: totalNum, }, ...app.config.msg.GET_SUCCESS } : app.config.msg.GET_ERR; }
可以看到,通過this.ctx.model.Book就可以獲取到Book的model并且可以調(diào)用mongoose需要的方法,例如populate、find、and、sort、skip、limit 等等。
5、egg-Mongoose常用的方法
增加數(shù)據(jù)
this.ctx.model.Book.create(data,callback);
其中data為json數(shù)據(jù)結(jié)構(gòu),callback為操作后的回調(diào)函數(shù)
查詢數(shù)據(jù)
獲取所有數(shù)據(jù),返回是一個數(shù)組
this.ctx.model.Book.find()
獲取一個數(shù)據(jù),返回是一個對象
this.ctx.model.Book.findOne()
條件查詢
this.ctx.model.Article.find(conditions,callback);
其中conditions為查詢的條件,callback為回調(diào)函數(shù)
conditions有一下幾種情況:
具體數(shù)據(jù):
this.ctx.model.Book.find({_id:5c4a19fb87ba4002a47ac4d, name: "射雕英雄傳" }, callback);
條件查詢:
"$lt" 小于"$lte" 小于等于"$gt" 大于"$gte" 大于等于"$ne" 不等于// 查詢價格大于100小于200的書籍數(shù)組this.ctx.model.Book.find({ "price": { $get:100 , $lte:200 });
或查詢 OR
"$in" 一個鍵對應(yīng)多個值"$nin" 同上取反, 一個鍵不對應(yīng)指定值"$or" 多個條件匹配, 可以嵌套 $in 使用"$not" 同上取反, 查詢與特定模式不匹配的文檔this.ctx.model.Book.find({"name":{ $in: ["射雕","倚天"]} );
刪除數(shù)據(jù)
this.ctx.model.Book.remove(conditions,callback);
更新數(shù)據(jù)
this.ctx.model.Book.update(conditions, update, callback)
conditions為條件,update是更新的值對象
排序
this.ctx.model.Book.sort({ create_time: -1 });
其中-1表示降序返回。 1表示升序返回
限制數(shù)量
this.ctx.model.Book.limit(number);
number表示限制的個數(shù)
跳過文檔返回
this.ctx.model.Book.skip(number);
number表示跳過的個數(shù),skip經(jīng)常搭配limit實現(xiàn)分頁的功能
條件數(shù)組and
在find后面可使用and對查詢結(jié)果進行進一步條件篩選,相當于并且的意思。
const search_term = { $or: [ { desc: { $regex: desc ? desc : '', $options: '$i' } }, { name: { $regex: desc ? desc : '', $options: '$i' } }, { author: { $regex: desc ? desc : '', $options: '$i' } }, { press: { $regex: desc ? desc : '', $options: '$i' } }, ], }; this.ctx.model.Book.find().and(search_term)
關(guān)聯(lián)查詢populate
// 在model中配置字段時候指定關(guān)聯(lián)的表名,就可以通過populate來進行表的關(guān)聯(lián)查詢user: { /* 書籍發(fā)布者id */ type: Schema.Types.ObjectId, ref: 'User', }, this.ctx.model.Book.find() .populate({ path: 'user', select: { name: 1, image: 1 } })
聚合管道Aggregate
this.ctx.model.Template.aggregate([ { $match: { name } }, { $sort: { create_time: -1 } }, { $group: { _id: '$name', user_id: { $first: '$modifier' } } }, ]);
Mongoose聚合管道aggregate常用的操作有$project 、$match 、$group、$sort、$limit、$skip、$lookup 表關(guān)聯(lián)
批量操作bulkWrite
const template_list = await ctx.model.Template.aggregate([ { $sort: { create_time: -1 } }, { $group: { _id: '$name', template_id: { $first: '$_id' }, label: { $first: '$label' } } }, ]); const update_value = []; template_list.forEach(item => { if (!item.label) { update_value.push({ updateOne: { filter: { _id: item.template_id }, update: { label: '' }, }, }); } }); await ctx.model.Template.bulkWrite(update_value);
可以進行一系列批量增加、刪除、更新等操作。
mongoose還有非常多的方法可以提供給我的靈活使用,我們在使用的時候可以結(jié)合業(yè)務(wù)邏輯選擇合適的方法來提高我們操作數(shù)據(jù)庫的效率。在我們使用它之前可以認真的閱讀官方文檔
總結(jié)
到此這篇關(guān)于Mongoose 在egg中的使用詳解的文章就介紹到這了,更多相關(guān)egg中使用Mongoose內(nèi)容請搜索武林網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持武林網(wǎng)!
新聞熱點
疑難解答