首页 > 解决方案 > Mongo 在 $lookup 结果中聚合 $match 和 $group

问题描述

我有节点文本 我有 3 个模型领导、用户和公司
我想使用领导模型获取所选公司 ID 的所有客户我尝试的是,使用 $lookup 和 $group 我得到了具有详细信息的唯一客户但是在添加 $match 之后我得到了空数组我希望有人能让我走上正轨..

****这是我的聚合代码****

const customers = await Lead.aggregate([
  {
    $match: { moving_company: companyId }, 
  },
 
  {
  $group: {
    _id: {
        "customer": "$customer",
        
    },
  }
},
  {
    $lookup: {
      from: "users",
      localField: "_id.customer",
      foreignField: "_id",
      as: "myCustomResut",
    },
  },


]);

这是我的公司模型

  const schemaOptions: mongoose.SchemaOptions = {
  _id: true,
  id: false,
  timestamps: true,
  skipVersioning: true,
  strict: false,
  toJSON: {
    getters: true,
    virtuals: true,
  },
};

export const CompanySchema = new mongoose.Schema(
  {
    name: {
      type: Schema.Types.String,
    },
  },
  schemaOptions
);

const Company = mongoose.model<ICompany>("Company", CompanySchema);
export default Company;

这是我的主要模特

    const schemaOptions: mongoose.SchemaOptions = {
  _id: true,
  id: false,
  timestamps: true,
  skipVersioning: true,
  strict: false,
  toJSON: {
    getters: true,
    virtuals: true,
  },
};

export const LeadSchema = new mongoose.Schema(
  {
    status: {
      type: Schema.Types.String,
    },
    customer: {
      type: Schema.Types.ObjectId,
      ref: Customer.modelName
    },
    assigned_sales_agent: {
      type: Schema.Types.String,
      ref: Agent.modelName
    },
    moving_company: {
      type: Schema.Types.ObjectId,
      ref:Company.modelName
    },
    selected_categories: [
      {
        type: SelectedCategorySchema,
       
      },
    ],

  },
  schemaOptions
);

const Lead = mongoose.model<ILead>("Lead", LeadSchema);
export default Lead;

这是我的客户模型

export const customerSchema = new mongoose.Schema(
  {
   
    address: {
      type: Schema.Types.ObjectId,
      ref: Addresses,
    },
  },
  UserSchemaOptions
);

export const Customer = User.discriminator<ICustomer>(
  "Customer",
  customerSchema,
  Role.CUSTOMER
);

export default Customer;

标签: node.jsreactjsmongodbaggregation-frameworkmongoose-schema

解决方案


推荐阅读