Вот рабочий образец с использованием mongoose v5.5.9
. Оказывается, отсутствующей частью является запись схемы index: { expires: '1m' }
в поле createdAt
.
const mongoose = require('mongoose')
// $ npm install uuid
const uuid = require('uuid')
const ObjectId = mongoose.Types.ObjectId
// Avoid deprecation warnings
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
// Create the schema.
const verifySchema = new mongoose.Schema({
_userId: {
type: ObjectId,
required: true,
ref: 'User'
},
hash: { type: String, required: true },
createdAt: {
type: Date,
required: true,
default: Date.now,
index: { expires: '1m' }
}
},
{
collection: 'verify'
});
// Connect to mongodb.
mongoose.connect('mongodb://localhost/test').then(() => {
// Create the model
const Verify = mongoose.model('Verify', verifySchema)
// Create a model instance.
const v = new Verify({
_userId: new ObjectId(),
hash: uuid.v4()
})
// Save the model.
v.save().then(() => {
// Close the connection.
mongoose.connection.close()
})
})
Вы можете проверить свои индексы с помощью MongoDB Compass или с помощью оболочки:
> use test
> db.verify.getIndexes()
Найдите значение поля expireAfterSeconds
, которое будет указывать время TTL в секундах, установленное для индекса. Чтобы изменить TTL, вам нужно сбросить индекс на createdAt
. В оболочке команда будет db.verify.dropIndex(<index_name>)
или db.verify.dropIndexes()
для удаления всех индексов в коллекции.
Для загрузки документов, таких как findOneAndUpdate , вам нужно будет передать setDefaultsOnInsert: true
таким параметрам:
// Connect to mongodb.
mongoose.connect('mongodb://localhost/test').then(() => {
// Create the model
const Verify = mongoose.model('Verify', verifySchema)
const _userId = new ObjectId()
const hash = uuid.v4()
const options = { upsert: true, setDefaultsOnInsert: true }
// Upsert the document.
Verify.findOneAndUpdate( { _userId }, { hash }, options).then(() => {
mongoose.connection.close()
})
})
Это необходимо, иначе поле createdAt
, содержащее индекс TTL, не будет добавлено в документ.