问题描述
我正在尝试使用 Mongoose 作为 MongoDB 的 ODM 和我的 node.js 应用程序.我注意到,当我设计一个带有嵌入式文档的模式时,如果我不向它添加值,它会在 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
}
这篇关于为什么猫鼬添加空白数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!