猫鼬为什么要添加空白数组? [英] Why does Mongoose add blank arrays?
问题描述
我正尝试通过我的node.js应用程序将Mongoose用作MongoDB的ODM.我注意到,当我设计带有嵌入式文档的架构时,如果不向其添加值,它将在Mongo中存储一个空白数组"[]".为什么是这样?我正在尝试将历史更改存储到记录中,而空白数组将意味着该更改删除了该值.这是示例架构.
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?
推荐答案
您可以通过定义以下架构来解决:
You can workaround by define the schema like below:
products: {
type: [{
name:String,
startDate:Date,
endDate:Date
}],
default: undefined
}
这篇关于猫鼬为什么要添加空白数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!