Why does Mongoose add blank arrays?

2019-01-23 02:50发布

问题:

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?

回答1:

Blank array gives you convenient way to add or remove elements from your Model.

$push $addToSet $pull in update would help you to manage your array elements.

If you don't have a blank array then you cannot push elements to null

But it is possible in blank array.



回答2:

You can workaround by define the schema like below:

products: {
  type: [{
    name:String,
    startDate:Date,
    endDate:Date
  }],
  default: undefined
}


回答3:

This seems to be by design, but there is a workaround here using a 'pre' handler to remove the default empty array: https://github.com/LearnBoost/mongoose/issues/1335

This only worked for me when I set the field to null, though. If I set it to undefined as in the sample code, the empty array seems to come back.



回答4:

Because in your schema you are defining products to be an array of objects. You would need to try something like:

products: {
        name:{type:String, index:true},
        startDate:Date,
        endDate:Date
    },

This will store an empty object instead of an array.