【发布时间】:2019-04-16 23:51:12
【问题描述】:
我希望架构中的特定字段成为一个包含项目的数组。
当我创建有问题的文档时,我不会有任何数组项。因此,我希望我的文档看起来像:
{
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()
【问题讨论】:
-
什么是
NotesSchema?不在您的代码中。它也可能应该是type: [NotesSchema],因为()意味着调用一个函数,而不是像你在这里应该做的那样分配一个“模式类型”。 -
抱歉,我已经解决了。我实际上将架构更改为
new....而没有从函数返回,但我仍然得到一个第一个值为空的数组。我希望这是有道理的。 -
再一次你不这样做
new。就像我已经(和文档一样)向您展示的那样做。type: [SubDocumentSchema]。没有new,也没有括号()。你在那里使用它就像在你的mongoose.model调用.model('DocumentSchema', DocumentSchema)中的第二个参数一样,没有new,也没有括号()。 -
我可能会误解,但是 Mongoose docs 确实指定实例化一个新的模式子文档。
-
你误会了。
const SubDocumentSchema = new Schema({ ...无论是模型的根、数组还是属性,“所有模式”都是一样的。所以没有function(),没有返回函数,当然也没有调用。 “调用”实际上是创建“空字符串”的原因。另请参阅mongoosejs.com/docs/subdocs.html
标签: arrays mongodb mongoose mongoose-schema