Problem with _ensureIndex


#1

I’m trying to create a document with a TTL

I got error MongoError: Values in v:2 index key pattern cannot be of type date. Only numbers > 0, numbers < 0, and strings are allowed.

Don’t know what i should do.

Meteor.startup(() => {
LaptopConnections._ensureIndex({ creationDate:new Date() }, { expireAfterSeconds:120});// Will delete the collection after two minutes,
});
Meteor.methods({
  
create_laptopconnection (lap_id) {

  check(lap_id, String);
  if (!LaptopConnections.findOne({_id: lap_id})) {
/* Insert a new Brief of the laptop */
LaptopConnections.insert({
      _id: lap_id,
      creationDate: new Date()
    });
  }else{
      
      LaptopConnections.update({_id: lap_id},{upsert:true},{
          $set: {
              "state.date": Date.now(),
              creationDate:  Date.now()
          }
        }
      ),{ multi: true };

  }
 
}
})
laptop.js ( collections ) 

LaptopConnections = new Mongo.Collection('laptopconnection');

let LaptopConnectionSchema = new SimpleSchema({
  creationDate : {
    type: Date,
    label: "Date when the laptop was created",
    // defaultValue: new Date()
    autoValue: function(){
      return new Date;
    }
  },
  "state.date" : {
    type: Date,
    label: "time when the laptop was created",
    autoValue: function(){
      return new Date;
    }
  }
}
,{timestamps: true}
)


LaptopConnections.attachSchema(LaptopConnectionSchema)

#2

LaptopConnections._ensureIndex({ creationDate: new Date() }, { expireAfterSeconds: 120 });

should be:

LaptopConnections._ensureIndex({ creationDate: 1 }, { expireAfterSeconds: 120 }); // default ascending order

or

LaptopConnections._ensureIndex({ creationDate: -1 }, { expireAfterSeconds: 120 }); // default descending order

Check the docs here


#3

You can not create index like this.
it you need to create index on 2 fields creationDate and expireAfterSeconds, it should be:

LaptopConnections._ensureIndex({ creationDate: 1, expireAfterSeconds: 1 });

Read more about indexing at https://docs.mongodb.com/manual/indexes/


#4

The OP wants to create a TTL index, not a compound index :slight_smile:.


#5

Oops! my bad :slight_smile: haha.


#6

Hello sir thank you for your response, when i lunch the application the collection is created but without document, didn’t understand what’s going on.


#7

There’s not enough information to answer that.

Do you have a link to the repo?


#8

It’s ok thank you i just deleted the collection, re-run my application and worked like a charm