3

Objective

To create uniqueness for two columns

what i tried

Here is my schema,

var mongoose = require('mongoose');

// location table Schema

var locationSchema = new mongoose.Schema({

    locationId: { type: String, required: true },
    stockingLocationId: { type: String, required: true},
    parentStockingLocationId: { type: String },
    stockingLocationDescription: { type: String },
    created: { type: Date, default: Date.now  },
    lastModified: { type: Date, default: Date.now },
    isActive: { type: Boolean , default : true },
    isDeleted: { type: Boolean , default : false }

});

Two columns are locationId and stockingLocationId.

I tried locationSchema.index({locationId:1, stockingLocationId:1}, { unique: true });

but not works,

Any help Please?

chiwangc
  • 3,566
  • 16
  • 26
  • 32
ramamoorthy_villi
  • 1,939
  • 1
  • 17
  • 40

5 Answers5

11

It worked for me, after adding single quotes around the fields like below

mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
smali
  • 4,687
  • 7
  • 38
  • 60
  • Worked for me after adding quotes to field name. Cheers! – Bharat Modi Feb 12 '19 at 09:03
  • 4
    TWO THINGS: this should be the OFFICIAL ANSWER, and also, mongoose developers should be fired. – Fer Martin Mar 19 '20 at 00:45
  • @FerMartin This has nothing to do with Mongoose devs; this is how all [all objects work in Javascript](https://stackoverflow.com/questions/4348478/what-is-the-difference-between-object-keys-with-quotes-and-without-quotes). – Mike Aug 24 '20 at 06:41
  • @Mike I believe 'filed1' is a valid identifier in javascript, therefore following your link, there should not be any difference, correct? – Fer Martin Apr 22 '21 at 09:21
  • @FerMartin That is correct. As long as your object property names are valid identifier names, you don't need to put quotes around them. – Mike Apr 22 '21 at 14:25
9

I know it's a little late but something along these lines..

mySchema.index({field1: 1, field2: 1}, {unique: true});

as specified in here

Community
  • 1
  • 1
Ocirne
  • 313
  • 6
  • 15
5

You need to drop your db after you change your index schema

hiddenrebel
  • 79
  • 1
  • 4
0

I think you have to make separate calls for the two columns. The way you do it, the combination of the two columns will be unique (combined unique key).

locationSchema.index({locationId:1}, { unique: true });
locationSchema.index({stockingLocationId:1}, { unique: true });
Markus
  • 1,598
  • 2
  • 13
  • 32
0

You can set it as following in your schema itself:

 locationId: { type: String, required: true, unique:true, index:true },
 stockingLocationId: { type: String, required: true, unique:true, index:true},
Deeksha Sharma
  • 3,199
  • 1
  • 19
  • 16