Mongo DB文档到期后没有删除

时间:2019-05-19 20:45:02

标签: node.js mongodb express mongoose

我正在尝试建立一个模型,以便在添加表时具有到期日期,在到期后,表将自行删除。我尝试过这样实现:

expires: '1m'

expires: 10

我有一个如下所示的表格:

const verifySchema = new mongoose.Schema({
    _userId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    hash: { type: String, required: true },
    createdAt: { type: Date, required: true, default: Date.now, expires: '1m' }
});

问题是,几分钟后什么也没发生。它不会在数据库中被删除。我做错什么了吗?

一分钟后如何删除表格?

1 个答案:

答案 0 :(得分:1)

这是使用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或使用Shell检查索引:

> 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()
  })
})

这是必需的,否则包含TTL索引的createdAt字段将不会添加到文档中。