時間:2024-02-05 12:47作者:下載吧人氣:31
實際開發(fā)過程中,為便于開發(fā)人員定位問題,常存在多個額外的字段。例如:增加createdAt、updatedAt字段以查看數(shù)據(jù)的創(chuàng)建和更改時間。而對于客戶端而言,無需知道其存在。針對以上情況,本文詳細(xì)介紹了“額外”字段的用途以及處理過程。
技術(shù)棧
mongodb中,collection中存儲的字段并不僅僅有業(yè)務(wù)字段。有些情況下,會存儲多余的字段,以便于開發(fā)人員定位問題、擴(kuò)展集合等。
額外的含義是指 和業(yè)務(wù)無關(guān)、和開發(fā)相關(guān)的字段。這些字段不需要被用戶所了解,但是在開發(fā)過程中是至關(guān)重要的。
產(chǎn)生額外字段的原因是多種多樣的。
額外字段的產(chǎn)生原因有很多,可以以此進(jìn)行分類。
產(chǎn)生原因:以mongoose為例,通過schema->model->entity向mongodb中插入數(shù)據(jù)時,該數(shù)據(jù)會默認(rèn)的增加_id、__v字段。
_id字段是由mongodb默認(rèn)生成的,用于文檔的唯一索引。類型是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首次創(chuàng)建時默認(rèn)生成,表示該條doc的內(nèi)部版本號。
“
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字段是實現(xiàn)軟刪除一種常用的方式。在實際業(yè)務(wù)中,出于各種原因(如刪除后用戶要求再次恢復(fù)等),往往采用的軟刪除,而非物理刪除。
因此,is_deleted字段保存當(dāng)前doc的狀態(tài)。is_deleted字段為true時,表示當(dāng)前記錄有效。is_deleted字段為false時,表示當(dāng)前記錄已被刪除。
_id字段是必選項;__v、createdAt、updatedAt字段是可配置的;status字段直接加在s對應(yīng)的chema中。相關(guān)的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});
網(wǎng)友評論