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?
exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.
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.
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.
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.
You can workaround by define the schema like below:
products: { type: [{ name:String, startDate:Date, endDate:Date }], default: undefined }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With