最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mongoose 在egg中的使用詳解

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

Mongoose是什么?

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

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

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 }, /* 價(jià)格 */
 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的方法對文檔進(jìn)行增刪查改了,已書籍列表的處理邏輯為例子

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" 不等于
// 查詢價(jià)格大于100小于200的書籍?dāng)?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實(shí)現(xiàn)分頁的功能

條件數(shù)組and

在find后面可使用and對查詢結(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中配置字段時候指定關(guān)聯(lián)的表名,就可以通過populate來進(jìn)行表的關(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);

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

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

總結(jié)

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

相關(guān)文章

  • MongoDB查詢之高級操作詳解(多條件查詢、正則匹配查詢等)

    MongoDB查詢之高級操作詳解(多條件查詢、正則匹配查詢等)

    這篇文章主要給大家介紹了關(guān)于MongoDB查詢之高級操作(多條件查詢、正則匹配查詢等)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • Mongodb 崩潰報(bào)錯 Too many open files的問題解析

    Mongodb 崩潰報(bào)錯 Too many open files的問題解析

    這篇文章主要介紹了Mongodb 崩潰報(bào)錯 Too many open files的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • MongoDB賬戶密碼設(shè)置的方法詳解

    MongoDB賬戶密碼設(shè)置的方法詳解

    這篇文章主要給大家介紹了關(guān)于MongoDB賬戶密碼設(shè)置的相關(guān)資料,我們知道m(xù)ysql在安裝的時候需要我們設(shè)置一個數(shù)據(jù)庫默認(rèn)的用戶名和密碼,mongodb也不例外,需要的朋友可以參考下
    2023-09-09
  • Ubuntu16.04手動安裝MongoDB的詳細(xì)教程

    Ubuntu16.04手動安裝MongoDB的詳細(xì)教程

    本篇文章主要介紹了Ubuntu16.04手動安裝MongoDB的詳細(xì)教程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • MongoDB 副本集的搭建過程

    MongoDB 副本集的搭建過程

    這篇文章主要介紹了MongoDB 副本集的搭建過程,幫助大家更好的理解和學(xué)習(xí)使用MongoDB數(shù)據(jù)庫,感興趣的朋友可以了解下
    2021-03-03
  • 【MongoDB for Java】Java操作MongoDB數(shù)據(jù)庫

    【MongoDB for Java】Java操作MongoDB數(shù)據(jù)庫

    本篇文章現(xiàn)在我們就用Java來操作MongoDB的數(shù)據(jù)。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-12-12
  • MongoDB學(xué)習(xí)筆記之分組(group)使用示例

    MongoDB學(xué)習(xí)筆記之分組(group)使用示例

    這篇文章主要介紹了MongoDB學(xué)習(xí)筆記之分組(group)使用示例,本文直接給出一組測試數(shù)據(jù),然后練習(xí)分組的基本使用,需要的朋友可以參考下
    2015-07-07
  • MongoDB學(xué)習(xí)筆記—Linux下搭建MongoDB環(huán)境

    MongoDB學(xué)習(xí)筆記—Linux下搭建MongoDB環(huán)境

    本篇文章主要介紹了Linux下搭建MongoDB環(huán)境,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-11-11
  • express使用Mongoose連接MongoDB操作示例【附源碼下載】

    express使用Mongoose連接MongoDB操作示例【附源碼下載】

    這篇文章主要介紹了express使用Mongoose連接MongoDB操作,結(jié)合實(shí)例形式分析了express使用Mongoose連接MongoDB的具體步驟與相關(guān)實(shí)現(xiàn)技巧,并附帶源碼供讀者下載參考,需要的朋友可以參考下
    2019-07-07
  • mongodb數(shù)據(jù)遷移詳細(xì)步驟(親測成功!)

    mongodb數(shù)據(jù)遷移詳細(xì)步驟(親測成功!)

    在數(shù)據(jù)驅(qū)動的時代,MongoDB作為非關(guān)系型數(shù)據(jù)庫的佼佼者,以其靈活的文檔模型、高可用性和可擴(kuò)展性,這篇文章主要介紹了mongodb數(shù)據(jù)遷移的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2025-01-01

最新評論

米泉市| 资溪县| 绥棱县| 秦皇岛市| 怀远县| 宁城县| 庄浪县| 舒兰市| 灵宝市| 竹北市| 西乌珠穆沁旗| 宁乡县| 台北县| 江北区| 轮台县| 东丰县| 交城县| 子长县| 留坝县| 栾川县| 惠安县| 顺昌县| 泸西县| 灵山县| 博兴县| 丹阳市| 卫辉市| 阿拉尔市| 南安市| 甘泉县| 象山县| 临潭县| 阳原县| 湾仔区| 蒙山县| 临泉县| 图木舒克市| 桓台县| 左云县| 灌云县| 安塞县|