欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Mongoose 在egg中的使用詳解

 更新時(shí)間:2020年06月12日 10:21:39   作者:YoLinDeng  
這篇文章主要介紹了Mongoose 在egg中的使用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

Mongoose是什么?

Mongoose是MongoDB的一個(gè)對(duì)象模型工具,封裝了許多MongoDB對(duì)文檔的的增刪改查等常用方法,讓NodeJS操作Mongodb數(shù)據(jù)庫(kù)變得更加靈活簡(jiǎn)單。

在egg項(xiàng)目中如何使用?

1、安裝

npm i egg-mongoose --save

2、配置

在根目錄下的/config/plugin.js中配置插件

exports.mongoose = {
 enable: true,
 package: 'egg-mongoose',
};

3、連接數(shù)據(jù)庫(kù)

在根目錄下的/config/config.default.js增加配置,其中url為我們的數(shù)據(jù)庫(kù)地址,可通過(guò)環(huán)境變量來(lái)區(qū)分開(kāi)發(fā)環(huán)境還是生產(chǎn)環(huán)境,并且確定是否使用用戶名密碼的數(shù)據(jù)庫(kù)
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)容,下面以書(shū)籍表的配置為例

'use strict';

/**
 * @description: Mongoose book Schema,
 */

module.exports = app => {
 const mongoose = app.mongoose;
 const Schema = mongoose.Schema;
 const BookSchema = new Schema({
 desc: { type: String }, /* 書(shū)籍描述 */
 name: { type: String }, /* 書(shū)籍名稱 */
 press: { type: String }, /* 出版社 */
 author: { type: String }, /* 作者 */
 image: { type: Array }, /* 書(shū)籍圖片列表*/
 price: { type: String }, /* 價(jià)格 */
 book_type: { /* 書(shū)籍分類id */
 type: Schema.Types.ObjectId,
 ref: 'BookClassify',
 },
 user: { /* 書(shū)籍發(fā)布者id */
 type: Schema.Types.ObjectId,
 ref: 'User',
 },
 create_time: { type: String }, /* 創(chuàng)建時(shí)間 */
 status: { type: String }, /* 狀態(tài),1:待購(gòu)買,2:已購(gòu)買*/
 look: { type: Number } /* 瀏覽數(shù)量 */
 });
 return mongoose.model('Book', BookSchema);
};

可以看到我們可以通過(guò)Schema來(lái)定義表結(jié)構(gòu),可以指定字段的類型及關(guān)聯(lián),設(shè)置完字段后就可以生成model了,這里算是非常簡(jiǎn)單的配置,更多配置方法可參考文檔

(2)、使用mongoose方法

配置完數(shù)據(jù)表結(jié)構(gòu)后,我們就可以再service層中調(diào)用mongoose的方法對(duì)文檔進(jìn)行增刪查改了,已書(shū)籍列表的處理邏輯為例子

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;
 }

可以看到,通過(guò)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ù),返回是一個(gè)數(shù)組

this.ctx.model.Book.find()

獲取一個(gè)數(shù)據(jù),返回是一個(gè)對(duì)象

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" 不等于
// 查詢價(jià)格大于100小于200的書(shū)籍?dāng)?shù)組
this.ctx.model.Book.find({ "price": { $get:100 , $lte:200 }); 

或查詢 OR

"$in" 一個(gè)鍵對(duì)應(yīng)多個(gè)值
"$nin" 同上取反, 一個(gè)鍵不對(duì)應(yīng)指定值
"$or" 多個(gè)條件匹配, 可以嵌套 $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是更新的值對(duì)象

排序

this.ctx.model.Book.sort({ create_time: -1 });

其中-1表示降序返回。 1表示升序返回

限制數(shù)量

this.ctx.model.Book.limit(number);

number表示限制的個(gè)數(shù)

跳過(guò)文檔返回

this.ctx.model.Book.skip(number);

number表示跳過(guò)的個(gè)數(shù),skip經(jīng)常搭配limit實(shí)現(xiàn)分頁(yè)的功能

條件數(shù)組and

在find后面可使用and對(duì)查詢結(jié)果進(jìn)行進(jìn)一步條件篩選,相當(dāng)于并且的意思。

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中配置字段時(shí)候指定關(guān)聯(lián)的表名,就可以通過(guò)populate來(lái)進(jìn)行表的關(guān)聯(lián)查詢
user: { /* 書(shū)籍發(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);

可以進(jìn)行一系列批量增加、刪除、更新等操作。

mongoose還有非常多的方法可以提供給我的靈活使用,我們?cè)谑褂玫臅r(shí)候可以結(jié)合業(yè)務(wù)邏輯選擇合適的方法來(lái)提高我們操作數(shù)據(jù)庫(kù)的效率。在我們使用它之前可以認(rèn)真的閱讀官方文檔

總結(jié)

到此這篇關(guān)于Mongoose 在egg中的使用詳解的文章就介紹到這了,更多相關(guān)egg中使用Mongoose內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MongoDB 查詢操作的實(shí)例詳解

    MongoDB 查詢操作的實(shí)例詳解

    這篇文章主要介紹了MongoDB 查詢操作的實(shí)例的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下
    2017-09-09
  • MongoDB學(xué)習(xí)之Text Search文本搜索功能

    MongoDB學(xué)習(xí)之Text Search文本搜索功能

    這篇文章主要給大家介紹了MongoDB之Text Search文本搜索功能的相關(guān)資料,文中給出了詳細(xì)的示例代碼供大家參考學(xué)習(xí),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。
    2017-05-05
  • 1億條記錄的MongoDB數(shù)據(jù)庫(kù)隨機(jī)查詢性能測(cè)試

    1億條記錄的MongoDB數(shù)據(jù)庫(kù)隨機(jī)查詢性能測(cè)試

    這篇文章主要為大家分享下1億條記錄的MongoDB數(shù)據(jù)庫(kù)隨機(jī)查詢性能測(cè)試結(jié)果,需要的朋友可以參考下
    2013-12-12
  • MongoDB中唯一索引(Unique)的那些事

    MongoDB中唯一索引(Unique)的那些事

    這篇文章主要給大家介紹了關(guān)于MongoDB中唯一索引(Unique)的那些事,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01
  • 關(guān)于CentOS 8 搭建MongoDB4.4分片集群的問(wèn)題

    關(guān)于CentOS 8 搭建MongoDB4.4分片集群的問(wèn)題

    在MongoDB里面存在另一種集群,就是分片技術(shù),可以滿足MongoDB數(shù)據(jù)量大量增長(zhǎng)的需求。這篇文章主要介紹了CentOS 8 搭建MongoDB4.4分片集群的問(wèn)題,需要的朋友可以參考下
    2021-10-10
  • mongodb的安裝和開(kāi)機(jī)自啟動(dòng)詳細(xì)講解

    mongodb的安裝和開(kāi)機(jī)自啟動(dòng)詳細(xì)講解

    這篇文章主要介紹了mongodb的安裝和開(kāi)機(jī)自啟動(dòng)詳細(xì)講解,,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 解決net start MongoDB 報(bào)錯(cuò)之服務(wù)名無(wú)效的問(wèn)題

    解決net start MongoDB 報(bào)錯(cuò)之服務(wù)名無(wú)效的問(wèn)題

    這篇文章主要介紹了解決net start MongoDB 報(bào)錯(cuò)之服務(wù)名無(wú)效的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • MongoDB索引使用詳解

    MongoDB索引使用詳解

    索引,使用索引可快速訪問(wèn)數(shù)據(jù)庫(kù)表中的特定信息。索引是對(duì)數(shù)據(jù)庫(kù)表中一列或多列的值進(jìn)行排序的一種結(jié)構(gòu),例如 employee 表的姓名(name)列。如果要按姓查找特定職員,與必須搜索表中的所有行相比,索引會(huì)幫助您更快地獲得該信息。
    2016-01-01
  • 修復(fù) Mac brew 安裝 mongodb 報(bào) Error: No available formula with the name ‘mongodb’ 問(wèn)題詳解

    修復(fù) Mac brew 安裝 mongodb 報(bào) Error: No available formula with th

    最近在同事新的 Mac 電腦上安裝 mongodb,報(bào)了錯(cuò)誤 Error: No available formula with the name ‘mongodb’,今天就說(shuō)說(shuō)這個(gè)問(wèn)題如何解決,需要的朋友可以參考下
    2020-02-02
  • 詳解mongodb搭建Replica Set的方法

    詳解mongodb搭建Replica Set的方法

    這篇文章主要介紹了mongodb搭建Replica Set的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12

最新評(píng)論