【问题标题】:What's the difference between sub-docs and nested objects in Mongoose?Mongoose 中的子文档和嵌套对象有什么区别?
【发布时间】:2014-12-20 09:27:59
【问题描述】:

在猫鼬模式中有两种定义嵌套对象的方法

var childSchema = new Schema({
  name: String,
  age: Number
})

var parentSchema = new Schema({
  children: [childSchema]
})

var parentSchema = new Schema({
  children: [{
    name: String,
    age: Number
  }]
})

那么它们之间有什么区别?我应该如何选择使用哪一个?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    同样的事情。在第二个版本中省略显式的childSchema 定义只是一个alternate declaration syntax

    唯一的区别是您是否有权访问子文档的架构对象(在第二个版本中您没有childSchema)。使用第一个版本的一个原因是,如果您需要在子架构上设置 option,例如在您不希望的情况下抑制 _id 字段。

    var childSchema = new Schema({
      name: String,
      age: Number
    }, {
      _id: false
    });
    

    您将无法使用替代语法来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2011-01-13
      • 1970-01-01
      相关资源
      最近更新 更多