婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > mongoDB使用投影剔除‘額外’字段的操作過程

mongoDB使用投影剔除‘額外’字段的操作過程

熱門標簽:智能外呼系統官網 外呼線路資源屬于電信業務嗎 小裙科技電銷機器人怎樣 呼和浩特外呼系統原理是什么 長沙電銷外呼防封卡是什么 河南電話外呼系統招商 crm外呼系統聯系方式 內蒙古營銷智能外呼系統哪個好 青白江400企業電話申請

簡介

實際開發過程中,為便于開發人員定位問題,常存在多個額外的字段。例如:增加createdAt、updatedAt字段以查看數據的創建和更改時間。而對于客戶端而言,無需知道其存在。針對以上情況,本文詳細介紹了“額外”字段的用途以及處理過程。

技術棧

  • mongodb 4.0.20
  • mongoose 5.10.7

1  "額外"字段是什么

1.1 "額外"是指與業務無關

mongodb中,collection中存儲的字段并不僅僅有業務字段。有些情況下,會存儲多余的字段,以便于開發人員定位問題、擴展集合等。

額外的含義是指 和業務無關、和開發相關的字段。這些字段不需要被用戶所了解,但是在開發過程中是至關重要的。

1.2 產生原因

產生額外字段的原因是多種多樣的。

  • 如使用mongoose插件向db中插入數據時,會默認的生成_id、__v字段
  • 如軟刪除,則是通過控制is_deleted實現..

2 額外字段的分類

額外字段的產生原因有很多,可以以此進行分類。

2.1 _id、__v字段

產生原因:以mongoose為例,通過schema->model->entity向mongodb中插入數據時,該數據會默認的增加_id、__v字段。

_id字段是由mongodb默認生成的,用于文檔的唯一索引。類型是ObjectID。mongoDB文檔定義如下:


MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.

__v字段是由mongoose首次創建時默認生成,表示該條doc的內部版本號。


The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The versionKey option is a string that represents the path to use for versioning. The default is __v.

2.2 createdAt、updatedAt字段

createdAt、updatedAt字段是通過timestamp選項指定的,類型為Date。


The timestamps option tells mongoose to assign createdAt and updatedAt fields to your schema. The type assigned is Date.By default, the names of the fields are createdAt and updatedAt. Customize the field names by setting timestamps.createdAt and timestamps.updatedAt.

2.3 is_deleted字段

is_deleted字段是實現軟刪除一種常用的方式。在實際業務中,出于各種原因(如刪除后用戶要求再次恢復等),往往采用的軟刪除,而非物理刪除。

因此,is_deleted字段保存當前doc的狀態。is_deleted字段為true時,表示當前記錄有效。is_deleted字段為false時,表示當前記錄已被刪除。

3 額外字段相關操作

3.1 額外字段生成

_id字段是必選項;__v、createdAt、updatedAt字段是可配置的;status字段直接加在s對應的chema中。相關的schema代碼如下:

isdeleted: {
 type: String,
 default:true,
 enum: [true, false],
},
id: {
 type: String,
 index: true,
 unqiue: true,
 default:uuid.v4(),
}},
{timestamps:{createdAt:'docCreatedAt',updatedAt:"docUpdatedAt"},versionKey:false});

通過配置schema中的timestamps選項,可以將createdAt和updatedAt字段加入到doc中。在創建和更新doc時,這兩個字段無需傳入,就會自動變化。

3.2 額外字段清理

通過3.1可以明確的產生若干額外字段,但是客戶端調用接口并返回時,這些字段是無需得知的。因此需對額外字段進行清理。清理方式分為投影和過濾。

以query、update接口為例。其中query接口用于:1、查詢指定字段 2、查詢全部字段 3、分頁排序查詢。update接口用于更新并返回更新后的數據。

根據是否需要指定字段、和collection中有無內嵌的情況劃分,一共有4類。接著針對這4種情況進行分析。

1、有指定字段、無內嵌

2、無指定字段、無內嵌

3、有指定字段、有內嵌

4、無指定字段、有內嵌

3.2.1 投影

有指定字段是指在查詢時指定查詢字段,而無需全部返回。mongo中實現指定的方式是投影 (project) 。mongo官方文檔中定義如下:


The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields.

$project可以做3件事:

1.指定包含的字段、禁止_id字段、添加新字段

2.重置已存在字段的值

3.指定排除的字段

我們只需關注事情1、事情3。接著查看mongoose中對project的說明:


When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

注意:此處指query "projection"

mongoose表明:投影要么是全包含,要么是全剔除。不允許包含和剔除同時存在。但由于

_id是MongoDB默認包含的,因此_id是個例外。

select project投影語句組裝代碼:

 /**
 * 添加通用篩選條件
 * @param {*} stat 已裝配的篩選語句 
 * @param {*} collection collectionName
 * @return {*} 組裝完成的語句
 */
 function addCommonSelectCond(stat,collection)
 {
 if(typeof(stat)!="object") return;

 stat["_id"] = 0;
 stat["__v"] = 0;
 stat["status"] = 0;
 stat["docCreatedAt"] = 0;
 stat["docUpdatedAt"] = 0;

 var embeddedRes = hasEmbedded(collection);
 if(embeddedRes["isEmbedded"])
 {
 for(var item of embeddedRes["embeddedSchema"])
 {
 stat[item+"._id"] = 0;
 stat[item+".__v"] = 0;
 stat[item+".status"] = 0;
 stat[item+".docCreatedAt"] = 0; 
 stat[item+".docUpdatedAt"] = 0; 
 }
 }
 return stat;
 }

3.2.2 過濾

通過findOneAndupdate、insert、query等返回的doc對象中(已經過lean或者toObject處理),是數據庫中真實狀態。因此需要對產生的doc進行過濾,包括doc過濾和內嵌文檔過濾。

/**
 * 處理自身及內嵌的表
 * @param {*} collection 查詢的表
 * @param {*} doc 已查詢出的結果
 * @returns doc 清理后的結果
 */
static clearDoc(collection,doc){
 if(doc === undefined || doc === null || typeof doc != "object" ) return null;
 doc = this.clearExtraField(doc);

 var res = hasEmbedded(collection);
 if(res["isEmbedded"])
 {
 let arr = res["embeddedSchema"];
 for(var item of arr){
 if(doc[item])
 doc[item] = this.clearArray(doc[item]);
 }
 }
 return doc;
}

static clearExtraField(doc){
 if(doc === null || typeof doc != "object")
 return;
 
 var del = delete doc["docCreatedAt"]
 delete doc["docUpdatedAt"]
 delete doc["_id"]
 delete doc["__v"]
 delete doc["status"];
 if(!del) return new Error("刪除額外字段出錯");

 return doc;
}

static clearArray(arr)
{
 if(!Array.isArray(arr)) return;

 var clearRes = new Array();
 for(var item of arr){
 clearRes.push(this.clearExtraField(item));
 }
 return clearRes;
}

細心的讀者已經發現了,投影和過濾的字段內容都是額外字段。那什么情況下使用投影,什么情況下使用過濾呢?

關于這個問題,筆者的建議是如果不能確保額外字段被剔除掉,那就采取雙重認證:查詢前使用投影,查詢后使用過濾。

4 總結

本文介紹了實際業務中往往會產生額外字段。而在mongoDB中,"消除"額外字段的手段主要是投影、過濾。

以使用頻率最高的查詢接口為例,整理如下:

指定選項 內嵌選項 查詢前投影 查詢后過濾
有指定 無內嵌 ×
有指定 有內嵌 ×
無指定 無內嵌 ×
無指定 有內嵌 ×

因此,筆者建議無論schema中是否配置了options,在查詢時組裝投影語句,查詢后進行結果過濾。這樣保證萬無一失,

額外字段才不會漏到客戶端**。

到此這篇關于mongoDB使用投影剔除‘額外'字段的文章就介紹到這了,更多相關mongoDB用投影剔除額外字段內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

標簽:菏澤 安順 黃石 呼倫貝爾 楚雄 池州 白山 舟山

巨人網絡通訊聲明:本文標題《mongoDB使用投影剔除‘額外’字段的操作過程》,本文關鍵詞  mongoDB,使用,投影,剔除,額外,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《mongoDB使用投影剔除‘額外’字段的操作過程》相關的同類信息!
  • 本頁收集關于mongoDB使用投影剔除‘額外’字段的操作過程的相關信息資訊供網民參考!
  • 企业400电话

    智能AI客服机器人
    15000

    在线订购

    合计11份范本:公司章程+合伙协议+出资协议+合作协议+股权转让协议+增资扩股协议+股权激励+股东会决议+董事会决议

    推薦文章
    主站蜘蛛池模板: 罗山县| 香港| 武威市| 横峰县| 巴彦淖尔市| 富阳市| 香河县| 拉孜县| 沈阳市| 江陵县| 鄂尔多斯市| 南召县| 扬州市| 华阴市| 张北县| 施秉县| 甘孜县| 福鼎市| 武定县| 台南县| 沙湾县| 吉林市| 都安| 古交市| 水城县| 宁乡县| 漳州市| 松溪县| 仙桃市| 绥江县| 土默特左旗| 栾川县| 大余县| 定远县| 拉萨市| 佛冈县| 海丰县| 色达县| 宁安市| 房山区| 东平县|