Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
451 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can workaround by define the schema like below:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...