【问题标题】:Sub-document in an array saves as an empty array item if no value is provided on document creation如果在创建文档时未提供值,则数组中的子文档将保存为空数组项
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-07-14
    • 1970-01-01
    • 2013-09-20
    • 2020-03-10
    • 2018-03-20
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多