文档中的空字段是否占用Mongoose中的空间? [英] Do empty fields in a document take up space in Mongoose?

查看:151
本文介绍了文档中的空字段是否占用Mongoose中的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不考虑使用继承或引用,而是考虑用所有可能的字段定义一个模式。因此,模式将有许多字段,其中一些将大多数时间是空的。空字段仍然占用数据库中的空间?我应该定义单独的模式吗?

解决方案

由于你使用Mongoose,答案涉及很多细微差别。 Mongoose将根据字段的类型做各种事情。如果您定义 类型的字段例如

  {
name:String,
age:Number
}

其中名称和年龄都不是必填字段。一旦你调用创建只有名称例如

  model.create {name:'Yuri'})

然后在数据库中, name defined



{_ id:ObjectId('....'),name:'Yuri'}



换句话说,mongoose不会存储年龄。



但另一方面,如果你有一个字段被声明为数组,例如

  {
name:String,
ages:[]
}

然后,如果你执行相同的 create 调用如上,它将导致以下文档:

  {_ id:ObjectId('...'),name:'Yuri',ages:[]} 
/ pre>

换句话说,即使你在创建调用中没有指定 ages ,mongoose你的数组。



TLDR:如果你的模式是平的,只由字符串和数字组成,那么mongoose不会将这些字段保存在db中,但它将用于对象和数组。


Instead of resorting to inheritance or references, I am thinking of defining one schema with all the possible fields. As a result, the schema will have many fields, some of which will be empty most of the times. Will the empty fields still take up space in the database? Should I define separate schemas instead?

解决方案

Since you're using Mongoose, the answer involves a lot of nuances. Mongoose will do various things depending on the type of field. If you define a field of type Number of String e.g.

{
  name: String, 
  age: Number
}

Where neither name nor age is a "required" field. Once you call create with just the name e.g.

model.create({name: 'Yuri'})

Then in your database, you will have an object with just the name defined

{_id: ObjectId('....'), name: 'Yuri' }

In other words, mongoose will not store the age.

But on the other hand, if you have a field that is declared as an array, e.g.

{
  name: String,
  ages: []
}

Then if you perform the same create call as above, it will result in the following document:

{_id: ObjectId('...'), name: 'Yuri', ages: []}

So in other words, even though you didn't specify ages in your create call, mongoose created the array for your anyway. The same mechanics apply to nested objects.

TLDR: if your schema is flat, and is composed of just strings and numbers, then mongoose will not save those fields in the db, but it will for objects and arrays.

这篇关于文档中的空字段是否占用Mongoose中的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆