2
votes

I know there are other questions about this issue; none, (that I have tried), have resolved my problem.

Using MongoDB 3.2.1, Mongoose 4.4.x, Node 0.12.9 or 4.2.6.

Mongoose Schema looks like:

var schema = new Schema({
  userId: {type: Schema.Types.ObjectId, ref: 'User', required: true},
  createdAt: {type: Date, required: true, default: Date.now, expires: 10}
});

Index is verified both in Mongo Shell and RoboMongo:

RoboMongo Index screencap

I've tried setting the TTL index on different fields, using different methods of creating the index, and some other things. Yet the documents remain, even after letting it sit overnight, and editing the createdAt field to be a time in the past.

Thoughts?

1

1 Answers

0
votes

I have MongoDB 3.2 and tested solution with following code snippet.

var MongoClient = require('mongodb').MongoClient,
    assert = require('assert'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var url = "mongodb://localhost:27017/test"
mongoose.connect(url);

var schema = new Schema({
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User', required: true
    },
    createdAt: {
        type: Date,
        required: true,
        default: Date.now,
        expires: 10
    }
});

var User = mongoose.model('User', schema);

var user = new User({ userId: new mongoose.Types.ObjectId });

user.save(function(err, doc) {
    if (err) {
        console.log(err);
    }
    mongoose.disconnect();
});

I see that document is getting expunged roughly after one minute (not exactly 10 seconds). I'd recommend you to get latest mongoose and try again.