从父架构填充字段

时间:2021-02-17 19:56:04

标签: mongodb mongoose

我有一个如下的交易架构:

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

以及一个有如下驱动字段的订单架构(每笔交易与一个订单相关)

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

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

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

这怎么可能?我尝试了如下虚拟,但没有用

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

1 个答案:

答案 0 :(得分:0)

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