Mongoose doesn't create TTL indexes

This is my Mongoose model:

var sessionSchema = new Schema({
    _id: { type: String, required: true, index: { unique: true } },
    user: { type: Schema.Types.ObjectId },
    expire: { type: Date, index: { expireAfterSeconds: 21600 } }
})
module.exports = mongoose.model('Session', sessionSchema)

I need to be able to set a date object into expire (usually it's something like Date.now plus a few minutes) and have the object removed from the collection after 6 hours past the expiration.

However, I'm not able to have Mongoose to create the index. When I run db.sessions.getIndexes() in the mongo console, here's the output:

[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "dev.sessions"
    }
]

I've tried also with different syntaxes, like
expire: { type: Date, expires: 21600 } (Mongoose's short-hand version).
I tried also defining the index at the schema level:
sessionSchema.index({ expire: 1 }, { expireAfterSeconds: 21600 })
None is working.

Unlike others who asked questions on SO, my index is simply not created. I've tried also removing the collection and the database as well, and when they're recreated they still don't contain the index.

Versions: Mongoose 3.8.19, MongoDB 2.6.5 (OSX) and Node.js 0.10.33

Edit

More info: I tried creating the index directly from the mongo console, with:
db.sessions.ensureIndex({"expire":1}, {expireAfterSeconds: 21600})
That appears to be working (the index is created).

However, it's not working with Mongoose in any way.


Apparently the problem was that I created an index on the custom _id field. MongoDB creates an index on that field by itself, so when Mongoose was calling ensureIndex to create also the TTL index, it failed for both.

See https://github.com/LearnBoost/mongoose/issues/2459

链接地址: http://www.djcxy.com/p/82446.html

上一篇: 在Javascript中查找字符串之间的区别

下一篇: Mongoose不会创建TTL索引