软件下载吧文章资讯

分类分类

mongoDB数据库基础 之 使用投影剔除‘额外’字段的操作过程

2024-02-05 12:47作者:下载吧

简介

实际开发过程中,为便于开发人员定位问题,常存在多个额外的字段。例如:增加createdAt、updatedAt字段以查看数据的创建和更改时间。而对于客户端而言,无需知道其存在。针对以上情况,本文详细介绍了“额外”字段的用途以及处理过程。

技术栈

mongodb中,collection中存储的字段并不仅仅有业务字段。有些情况下,会存储多余的字段,以便于开发人员定位问题、扩展集合等。

额外的含义是指 和业务无关、和开发相关的字段。这些字段不需要被用户所了解,但是在开发过程中是至关重要的。

1.2 产生原因

产生额外字段的原因是多种多样的。

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});
展开全部

相关文章

说两句网友评论
    我要跟贴
    取消