node.js - 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;
解决方案
推荐阅读
- sql - 如何使用一个参数过滤单个数据集中的多个值?
- python - 如何从属性文件中读取数据库名称?
- button - SwiftUI - 按钮 - 如何将函数请求传递给父级
- python - 如何仅注释查询集中的几个实例?
- python - 对所有行中不包括空格的总字符求和Python
- scala - 如何自定义 Gatling 的 HTMLReports
- javascript - Turbolinks 和初始化脚本
- strapi - 前端用户资料 - 最佳策略
- python - 你能提供一种不理解的方式来编写下面的代码吗
- extract - 表中的 Storetext 选择正确的行来存储 Selenium Ide Ui Vision Kantu