0

I am messing around with MongooseJS and trying to create a friend request where I store a to and from key in MongoDB which are the userId's of the sender and receiver. I want to prevent duplicate requests from the same sender to the same receiver.

Here is my Schema:

import { model, Schema, Document } from 'mongoose';
import { FriendRequestInterface } from '@interfaces/friendrequest.interface';
import { FriendRequestStatus } from '@/enums/enumFriendRequest';

const friendRequestSchema: Schema = new Schema({
  to: {
    type: String,
    required: true,
    // unique: true,
  },
  from: {
    type: String,
    required: true,
    // unique: true,
  },
  message: {
    type: String,
    required: false,
  },
  status: {
    type: String,
    enum: FriendRequestStatus,
    required: true,
  },
});

friendRequestSchema.index({ to: 1, from: 1 }, { unique: true });
const friendRequestModel = model<FriendRequestInterface & Document>('FriendRequest', friendRequestSchema);
export default friendRequestModel;

What I POST:

{
    "to": "636acf77378903f78b388339",
    "from": "636acf83378903f78b38833f",
    "message": "Hello, I want to be your friend.",
    "status": "pending"
}

POSTMAN ERROR:

{
    "message": "E11000 duplicate key error collection: db_dev.friendrequests index: from_1 dup key: { from: \"636acf83378903f78b38833f\" }"
}
Daly
  • 134
  • 5

1 Answers1

0

Apparently my issue was that I still had indexes set inside my collection in MongoDB which were interfering. I cleared all my indexes I made whilst messing around and added the index (compounding) this way:

friendRequestSchema.index({ to: 1, from: 1 }, { unique: true, sparse: true });

Where I removed my indexes and added my current one:

Daly
  • 134
  • 5