2

Mongodb how to enforce a unique db reference id?

const LikeSchema = new mongoose.Schema({
    idOfPost: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post',
        required: true,
    },
    userWhoLiked: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true,
        unique: true // This is not working? Why?
    },
    date=:{
        default: Date.now,
        required: true,
        type: Date,
    },

How can I make sure that all userWhoLiked fields are unique?

YulePale
  • 6,688
  • 16
  • 46
  • 95
  • 1
    If your "AutoIndex" is "off" you need to call https://mongoosejs.com/docs/api.html#model_Model.ensureIndexes explicitly. If you have documents that violate uniqueness the index won't be created. – Alex Blex Mar 11 '20 at 16:40
  • Does this answer your question? [Mongoose unique validation not working. Duplicate entries getting saved](https://stackoverflow.com/questions/59435708/mongoose-unique-validation-not-working-duplicate-entries-getting-saved) – SuleymanSah Mar 11 '20 at 17:51

1 Answers1

2

You should build a unique index, then in the case of an insert/update of a document with a duplicate userWhoLiked value you'll get duplicate key error thrown.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • At what point do you call `db.myCollection.createIndex()` is it after you have created your first document? Is it before? I am finding the docs a bit hard to understand. Where in the code do I place the createIndex command? – YulePale Mar 11 '20 at 16:51
  • 1
    You do it once , so you don't really need to incorporate it in your code. Just run it once – Tom Slabbaert Mar 11 '20 at 17:44
  • The reference you shared really helped me. – Rigin Oommen Aug 24 '21 at 11:25