Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Mongoose add blank arrays?

I am trying to start using Mongoose as an ODM for MongoDB with my node.js application. I have noticed that when I design a schema with an embedded document that if I don't add a value to it, it store a blank array "[]" in Mongo. Why is this? I am trying to store historical changes to records and a blank array would mean that that change deleted the value. Here is a sample schema.

schema.Client = new mongoose.Schema({     name:{type:String, required:true},     products:[{         name:{type:String, index:true},         startDate:Date,         endDate:Date     }],     subdomain:{type:String, index:{unique:true}}, }) 

Here is the resulting document when I save a document with just name and subdomain.

{     "name": "Smith Company",     "products": [],     "subdomain": "smith" } 

Why did it add products with a blank array by default and how can I stop it?

like image 485
wintzer Avatar asked Sep 30 '12 02:09

wintzer


People also ask

Does Mongoose create collection automatically?

exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.

Can I set default value in Mongoose schema?

As mentioned by user whoami, mongoose only sets defaults on insert. If you are using mongoose 4. x and up and MongoDB 2.4. 0 and up you can opt-in to setting default values on update too.

Is schema necessary for Mongoose?

not entirely true. There are realtime apps that can rely on fields created on the fly. Adding a field to Mongoose model means a new deploy process. There are ODMs that doesn't require a fixed schema definition, Mongorito for instance.

What is the difference between model and schema in Mongoose?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.


1 Answers

You can workaround by define the schema like below:

products: {   type: [{     name:String,     startDate:Date,     endDate:Date   }],   default: undefined } 
like image 193
Angelo Chen Avatar answered Sep 28 '22 14:09

Angelo Chen