0

Consider the database has the following records,

{id: 1, device: 'A'},
{id: 1, device: 'B'}

Now, If I want to insert {id: 1, device: 'A'} the record should not be created as id: 1 already exists for device A.

So, how will the Mongoose schema look?

Harsha W
  • 3,162
  • 5
  • 43
  • 77
Sridhar Sg
  • 1,546
  • 13
  • 21

1 Answers1

1

You can define compound index for this kind of purpose.

Your schema will look like this:

const DeviceSchema = new Schema({
    id: { type: Number },
    device: { type: String },
})

DeviceSchema.index({ id: 1, device: 1}, { unique: true });

For more info please visit this link

Tolsee
  • 1,695
  • 14
  • 23