How do I add validation to an embedded schema?

How do I add validation to this schema such that at least 1 property of account needs to be provided. It can be any 1 of the 4?

interface IPlan {
  accounts: {
    facebook?: string;
    instagram?: string;
    linkedin?: string;
    x?: string;
  };
}

const PlanSchema = new mongoose.Schema<IPlan>(
  {
    accounts: {
      facebook: {
        type: String,
      },
      instagram: {
        type: String,
      },
      linkedin: {
        type: String,
      },
      x: {
        type: String,
      },
    },
  },
  { timestamps: true }
);

export default mongoose.model<IPlan>('Plan', PlanSchema);

This is what I got for form validation like this, I changed it with what variables (double check) I could find in your original to hopefully make it easier for you to fit it.

It will need some changes of course (maybe) for your environment, as I don’t know what’s all in it. But without further ado, this is a template I use for this that validates if either of the fields have been filled.

import mongoose from 'mongoose';

interface IPlan {
  accounts: {
    facebook?: string;
    instagram?: string;
    linkedin?: string;
    socialmediasitehere?: string;
  };
}

const PlanSchema = new mongoose.Schema<IPlan>(
  {
    accounts: {
      type: Object,
      validate: {
        validator: function (accounts) {
          // Check if at least one property of the accounts object is provided
          return (
            accounts.facebook ||
            accounts.instagram ||
            accounts.linkedin ||
            accounts.socialmediasitehere
          );
        },
        message: 'At least one account property must be provided.',
      },
    },
    // Add the rest of your schema
  }
);

const PlanModel = mongoose.model<IPlan>('Plan', PlanSchema);

export default PlanModel;

This doesn’t work but I wish it did. What I’ve done is use a pre which feels wrong, adding the validation inside the schema as you did above seems best.

my hack
PlanSchema.pre("save", function () {
  const { facebook, instagram, linkedin, x } = this.accounts;
  if (
    facebook === undefined &&
    instagram === undefined &&
    linkedin === undefined &&
    x === undefined
  ) {
    throw new Error("At least one account property must be provided.");
  }
});

I didn’t do so much debugging as I should have, I was more so pushing to what direction to aim towards.

But if that works you got it, the issue is that there isn’t much documentation on this like there should be.

The code I posted works in the environment it’s in, I’m just not familiar enough with your environment to really tailor it.

I’ll keep trying things. Maybe convert it to an array of objects and try to validate the array, etc.

You’re right on the docs part, the most I’m seeing is the basic use of required.

Did this get figured out? What was the solution you came up with?