時間:2024-02-05 12:47作者:下載吧人氣:19
實際開發過程中,為便于開發人員定位問題,常存在多個額外的字段。例如:增加createdAt、updatedAt字段以查看數據的創建和更改時間。而對于客戶端而言,無需知道其存在。針對以上情況,本文詳細介紹了“額外”字段的用途以及處理過程。
技術棧
mongodb中,collection中存儲的字段并不僅僅有業務字段。有些情況下,會存儲多余的字段,以便于開發人員定位問題、擴展集合等。
額外的含義是指 和業務無關、和開發相關的字段。這些字段不需要被用戶所了解,但是在開發過程中是至關重要的。
產生額外字段的原因是多種多樣的。
額外字段的產生原因有很多,可以以此進行分類。
產生原因:以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.
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.
is_deleted字段是實現軟刪除一種常用的方式。在實際業務中,出于各種原因(如刪除后用戶要求再次恢復等),往往采用的軟刪除,而非物理刪除。
因此,is_deleted字段保存當前doc的狀態。is_deleted字段為true時,表示當前記錄有效。is_deleted字段為false時,表示當前記錄已被刪除。
_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});
網友評論