Skip to content
Advertisement

How do I use $addToSet with objects in mongodb?

I want to push only unique objects into an array with $addToSet.

My userSchema has a field bankDetails which should take an array of objects:

const userSchema = new mongoose.Schema(
  {
    bankDetails: [
      {
        cardHolder: String,
        cardNumber: String,
        expiry: String,
        cvc: String,
        cardBrand: String,
      },
    ]
  }
)

I am updating the schema using the following controller function:

exports.createPayment = async (req, res) => {
  const { user, cardHolder, cardNumber, expiry, cvc, cardBrand } = req.body
  const saveDetails = await User.findByIdAndUpdate(
    { _id: user._id },
    $addToSet: {
      bankDetails: {
        cardHolder,
        cardNumber,
        expiry,
        cvc,
        cardBrand,
      },
    },
    { new: true }
  ).exec();
  res.json(saveDetails);
}

The data is saving correctly but Mongo auto generates an _id field every time so technically none of the objects are unique and the objects are repeatedly added.

Is anyone aware of a workaround for this?

Advertisement

Answer

You could check if a bank already exists, and add it only if not present:

exports.createPayment = async (req, res) => {
  const { user, cardHolder, cardNumber, expiry, cvc, cardBrand } = req.body;
  const existingBank = await User.findOne({
    'bankDetails.cardHolder': cardHolder,
    'bankDetails.cardNumber': cardNumber,
    'bankDetails.expiry': expiry,
    'bankDetails.cvc': cvc,
    'bankDetails.cardBrand': cardBrand,
  });
  if (existingBank) return res.json(existingBank);
  const saveDetails = await User.findByIdAndUpdate(
    user._id,
    {
      $addToSet: {
        bankDetails: {
          cardHolder,
          cardNumber,
          expiry,
          cvc,
          cardBrand,
        },
      },
    },
    { new: true }
  ).exec();
  res.json(saveDetails);
};
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement