Home > Software design >  Is there a solution when mongodb query parameter null or exists?
Is there a solution when mongodb query parameter null or exists?

Time:11-17

I'm trying to make get customer & store from mongodb use mongoose Model,

getCustomer Function parameter are customer and store, But sometimes store parameter is null || undefined

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

// Find customer && Store
const getCustomer = async (customer, store) => {
  const result = await Customer.aggregate([
    {
      $match: {
        customerId: customer.id,
        storeId: store.id,
      },
    },
  ]);
  return result;
};

So this $match query in aggregate is return Error, Because store.id is not found.

Can you tell me what query I should use if store data is passed unconditionally?

CodePudding user response:

Pass the store.id conditionally, like this:

const getCustomer = async (customer, store) => {
  const result = await Customer.aggregate([
    {
      $match: {
        customerId: customer.id,
        ...(store && store.id ? { storeId: store.id } : {})
      },
    },
  ]);
  return result;
};
  • Related