【问题标题】:node js, mongodb populate the populated节点js,mongodb填充填充
【发布时间】:2018-03-28 21:01:52
【问题描述】:

当我需要从我的服务器获取数据时,我的服务器遇到了困难。 以下代表我的架构:

Schema one:{
name: String
}
Schema two:{
code:String,
name_id: refid: schema One
}
Schema three:{
phone:number
code:[refid: Schema two]
}

如果我需要来自模式 3 的数据,以及保存在代码数组中的对象 ID 中的对象,我将使用填充并获取对象 ID 引用的对象。 问题是否可以填充填充的数据? 如果填充模式三 我会得到以下对象:

{phone : 000911,
code: :{code:String,
name_id: refid: schema One}

在前面的示例中,我想填充名称 id,这可能吗?

【问题讨论】:

  • 是模式三 code: refid: 模式一还是二?你也在用猫鼬吗?
  • 模式三代码是从模式二中引用的,是的,我使用的是猫鼬

标签: node.js mongodb mongoose


【解决方案1】:

使用 Mongoose,您可以使用点符号填充您的架构,如下所示:

const One = new Schema({
  name: String
})

const Two = new Schema({
  code: String,
  name: {
    type: Schema.ObjectId,
    ref: 'One'
  }
})

const Three = new Schema({
  phone: number
  code: [{
    type: Schema.ObjectId,
    ref: 'Two'
  }]
})


Three.find((err, three) => {
  if (err) console.log(err)
  console.log(three)  
  // => {
  //      phone : "the phone number from schema Three",
  //      code: {
  //        code: "the code from schema Two",
  //        name: "the name from schema One"
  //      }
  //    }
})
.populate('code.name')

【讨论】:

  • 如果我需要另一个人口,假设是零模式,我需要从三到二到零填充
  • 这也适用于数组。如果您需要添加第三层,只需添加另一个点属性。见populate
猜你喜欢
  • 2017-06-10
  • 2015-11-19
  • 2018-10-14
  • 2015-06-20
  • 2021-01-25
  • 2019-06-25
  • 2014-09-03
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多