title: How can I set composite primary key in mongodb through mongoose
body: <p>I want to set primary key for two fields in a collection in <code>mongodb</code> through <code>mongoose</code>. I know to set composite primary key in <code>mongodb</code> as </p>
  
  <pre><code>db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )
  </code></pre>
  
  <p>but am using <code>mongoose</code> to handle <code>mongodb</code> I don't know how to set composite primary key from <code>mongoose</code></p>
  
  <p><strong>update</strong></p>
  
  <p>I used <code>mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });</code>
  see my code </p>
  
  <pre><code>var mongoose = require('mongoose')
  
  var uristring ='mongodb://localhost/fresh';
  var mongoOptions = { db: { safe: true } };
  
  // Connect to Database
  mongoose.connect(uristring, mongoOptions, function (err, res) {
      if (err) {
          console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
      } else {
          console.log ('Successfully connected to: remote' + uristring);
      }
  });
  var mySchema = mongoose.Schema({
          ColorScaleID:String,
          UserName:String,
          Range1:Number,
      })
  mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
  var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
  var myVar = new freshtime({
          ColorScaleID:'red',
          UserName:'tab',
          Range1:10
      })
  myVar.save()
  mongoose.connection.close();
  </code></pre>
  
  <p>When I execute this code for first time I see a line <code>{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }</code> in mongodb's fresh database. When I execute the same code for second time I see two same lines.</p>
  
  <pre><code>{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
  {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
  </code></pre>
  
  <p>If <code>composite primary key</code> worked then it shouldn't allow me to insert same data for second time. what would be the problem?</p>