node.jsmongodbexpressmongoose

How to solve Mongoose Schema storing empty array in the mongoDB


I am developing an API's using express and nodejs, the API stores data in mongoDB using mongoose, following is the schema I have designed.

const MessagesSchema = new mongoose.Schema(
  {
    readReceipt: {
      type: String,
      required: [true, "Read Receipt Mandatory"],
      enum: {
        values: ["sent", "received", "read"],
        message: `Ivalid value {VALUE}`,
      },
    },
    messageContent: { type: String },
    sentBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Users",
      required: [true, "Sender cannot be Empty"],
    },
    sentTo: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "Users",
      required: [true, "At Least One senderId required"],
    },
  },
  { timestamps: true }
);

Following is the output I get when the data is stored in the mongoDB.

{
    "readReceipt": "sent",
    "messageContent": "Test Message 4",
    "sentBy": "6728a8b1b6fd6ebeac8e0fa5",
    "sentTo": [],
    "_id": "672b2539d7f2f99e8f9ef738",
    "createdAt": "2024-11-06T08:13:45.080Z",
    "updatedAt": "2024-11-06T08:13:45.080Z",
    "__v": 0
}

sentTo field is an array of ObjectId's, as in the above output sentTo field is getting stored as an empty array, I want it to through an error when no value is passed, I tried passing required: true but it is not working. I searching internet for the issue but couldn't find anything specific to it.

I am using

I tried adding required:true in the schema but it is not working, I expect it to through an error when storing empty value.

any solution for this issue is appreciated, Thant You


Solution

  • Please give it a try by adding a validate/validator for sentTo field

    sentTo: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "Users",
      required: [true, "At Least One senderId required"],
      validate: {
        validator: function (v) {
          return v.length > 0;
        },
        message: 'The sentTo array cannot be empty',
      },