You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合查询中处理store参数为空的解决方案(Mongoose)

解决方案

你可以通过动态构建$match查询条件来处理store参数的可选情况,避免直接访问store.id导致的报错:

// Mongoose Model
const Customer = require("../models")

// Find customer && Store
const getCustomer = async (customer, store) => {
  // 初始化基础查询条件,确保customerId必选
  const matchConditions = {
    customerId: customer.id
  };

  // 仅当store存在且包含id字段时,添加storeId匹配条件
  if (store && store.id) {
    matchConditions.storeId = store.id;
  }

  const result = await Customer.aggregate([
    { $match: matchConditions }
  ]);
  return result;
};

关键说明

  • 先创建基础的matchConditions对象,保证customerId始终作为查询条件
  • 通过if (store && store.id)的判断,避免在store为null/undefined或无id时访问store.id引发错误
  • 当store参数有效时,自动追加storeId的匹配规则;无效时仅按客户ID查询

内容的提问来源于stack exchange,提问作者Morgan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:10:37