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?
-
Define "empty". Any definition of a "field" persisted in a data store or in fact "anywhere" is going to use "some space". Nothing is free. Unless of course it does not exist at all. – Blakes Seven Sep 10 '15 at 12:08
-
By 'empty' I mean the field is defined in the schema, but not included nor specified in the document to be saved. – Chong Lip Phang Sep 10 '15 at 12:17
-
Have you tried creating a document and then seeing what happens in such a case? Also the title *"..take up space in mongoose?"* is likely misleading to your intent. If you mean *"..stores data in database when I omit them.."** then a simple test should answer the question. And yet also this entirely depends on the actual schema definition which is notably missing from the question. As is also clarification in general of *"takes space"* as to storage? Or memory consumed by client? No idea which one you are asking. So you might actually try to make that clear. Or "try" storing something. – Blakes Seven Sep 10 '15 at 12:22
-
How would you suggest I design the simple test? A database is stored on the hard disk, but does that matter anyway? Why would one want to see the actual schema definition? – Chong Lip Phang Sep 10 '15 at 12:31
1 Answers
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.

- 11,439
- 4
- 30
- 33