如果在创建文档时未提供任何值,则数组中的子文档将保存为空数组项

Sub-document in an array saves as an empty array item if no value is provided on document creation

我想要的是我的模式中的特定字段是一个包含项目的数组。

当我创建有问题的文档时,我不会有任何数组项。因此,我希望我的文档看起来像:

{
  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()

您可以指定空数组作为注释的默认值。而且您不需要 return 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()