我希望模式中的特定字段是一个包含项的数组。
当我创建有问题的文档时,我将没有任何数组项。因此,我希望我的文档看起来像:
{
notes: []
}
问题是,我得到的数组看起来像:
{
notes: ['']
}
查询notes.length
,我得到1,这对我来说是有问题的,因为它本质上是一个空数组项。
这是我正在使用的代码:
const SubDocumentSchema = function () {
return new mongoose.Schema({
content: {
type: String,
trim: true
},
date: {
type: Date,
default: Date.now
}
})
}
const DocumentSchema = new mongoose.Schema({
notes: {
type: [SubDocumentSchema()]
}
});
const Document = mongooseConnection.model('DocumentSchema', DocumentSchema)
const t = new Document()
t.save()
您可以指定空数组作为注释的默认值。并且您不需要为SubDocumentSchema返回函数。请尝试下面编辑的代码。
const SubDocumentSchema = new mongoose.Schema({
content: {
type: String,
trim: true
},
date: {
type: Date,
default: Date.now
}
})
const DocumentSchema = new mongoose.Schema({
notes: {
type: [SubDocumentSchema],
default: []
}
});
const Document = mongooseConnection.model('DocumentSchema', DocumentSchema)
const t = new Document()
t.save()