首页 > 解决方案 > 从父模式填充字段

问题描述

我有一个事务架构如下:

  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({ name: String, })

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

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

标签: mongodbmongoose

解决方案



推荐阅读