Mongoose set default as empty object

Mongoose

Mongoose Problem Overview


I am trying to set the star_info attribute as an object type(Mixed Schema) and setting it's default value as an empty object using

star_info: { type : Schema.Types.Mixed, default : { }}

In the database, there is no field star_info when saving the documents. How do I get mongoose to set the default value?

Mongoose Solutions


Solution 1 - Mongoose

By default (in an effort to minimize data stored in MongoDB), Mongoose will not save empty objects to your database. You can override this behavior by setting the minimize flag to false when you create your schema. For example:

const schema = new Schema({
  star_info: { type: Schema.Types.Mixed, default: {} }
}, { minimize: false })

Now star_info will default to an empty object and save to the database.

Read more at http://mongoosejs.com/docs/guide.html#minimize

Solution 2 - Mongoose

If you don't mind empty objects being omitted from the database, but you want them in your JSON, just use obj.toJSON({minimize: false})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionma08View Question on Stackoverflow
Solution 1 - MongooseiamthegreenfairyView Answer on Stackoverflow
Solution 2 - MongooseAdam ReisView Answer on Stackoverflow