Problem with _ensureIndex

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)

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

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/

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

1 Like

Oops! my bad :slight_smile: haha.

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.

There’s not enough information to answer that.

Do you have a link to the repo?

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

1 Like