【问题标题】:populate field from parent schema从父模式填充字段
【发布时间】:2021-05-20 18:18:51
【问题描述】:

我有一个事务架构如下:

  const transactionSchema = mongoose.Schema(  {
       amount: Number,
       order: {
          type: mongoose.Schema.ObjectId,
          ref: 'Order'
        }
      },
      {
        toJson: { virtuals: true },
        toObject: { virtuals: true }
      }
    );

还有一个Order Schema,其驱动字段如下(每笔交易都与一个Order相关)

const orderSchema = mongoose.Schema(
  {
    title: String,
     driver: {
      type: mongoose.Schema.ObjectId,
      ref: 'User'
    })

当我查询(查找)事务时,我需要从用户架构中提取驱动程序名称 我的用户架构如下:

const userSchema = new mongoose.Schema({ 名称:字符串,})

这怎么可能?我尝试如下 virtuals 但它没有工作

transactionSchema.virtual('driverName', {
  ref: 'User',
  foreignField: 'name', //name of reference field in Review model
  localField: 'driver' //name of reference in local Model
});

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我发现这可以通过深度填充来解决(跨多个级别填充) 根据猫鼬docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2011-02-08
      相关资源
      最近更新 更多