Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can workaround by define the schema like below:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...