node.js - Mongo DB文档过期后不会删除

标签 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' }
});

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

如何在一分钟后删除表格?

最佳答案

这是一个使用 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 上的索引。 。在 shell 中,命令为 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 索引的字段不会添加到文档中。

关于node.js - Mongo DB文档过期后不会删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211850/

相关文章:

c# - 使用 C# .NET 驱动程序 2.0 投影 mongodb 子文档

node.js - 通过 Mongoose 模式将数据存储在mongodb中,不传递唯一真实键的值

c# - 我可以将 pocos 与 mongodb c# 驱动程序一起使用吗

mysql - 如何防止nodejs中的sql注入(inject)和 Sequelize ?

javascript - Socket.io和express.js,如何使其工作?

node.js - 在 Mountain Lion 上安装 32 位 Node

javascript - AngularJS 不存在 'Access-Control-Allow-Origin' header

node.js - Socket.io 和 Redis 发布/订阅

javascript - 为什么 Sequelize beforeUpdate 钩子(Hook)不起作用?

javascript - module.js 运行iron-node 时找不到模块