- 简介
实际开发过程中,为便于开发人员定位问题,常存在多个额外的字段。例如:增加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 p