node.js - Mongoose Schema 设置过期字段来删除文档?

标签 node.js mongodb mongoose

我想在文档创建 3 分钟后将其删除。定义文档创建时刻的字段是 expiresAt。这是我迄今为止的设置。该文档在 3 分钟后并未按其应有的方式删除。

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const PostsAmountsTimeframesSchema = new Schema({
  posts_amounts_timeframe: Number,
  expireAt: {
      type: Date,
      default: new Date()
  },
  userid: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
  },
})



PostsAmountsTimeframesSchema.index( { expireAt: 1 }, { expireAfterSeconds: 180 } )

const PostsAmountsTimeframes = mongoose.model('PostsAmountsTimeframes', PostsAmountsTimeframesSchema)

module.exports = PostsAmountsTimeframes

也尝试过

  expireAt: {
      type: Date,
      default: new Date(),
      expires: 180,
  }

相同的结果。

PS:这是在服务器上创建文档的方式:

PostsAmountsTimeframes.create({
      userid: req.session.userId,
      posts_amounts_timeframe: req.session.posts_amounts_timeframe,
      // expireAt: d
  }, (error, postsamountstimeframes) => {
      console.log(error)
})

最佳答案

解决方案

  • 删除整个集合
  • 删除集合中的所有索引
  • 将代码更改为:
const mongoose = require('mongoose')
//Create empty Schema object?
const Schema = mongoose.Schema


//Models are defined through the Schema interface
//Models define collections
const PostsAmountsTimeframesSchema = new Schema({
  posts_amounts_timeframe: Number,
  expireAt: {
      type: Date,
  },
  userid: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
  },
})

PostsAmountsTimeframesSchema.index({ expireAt: 1 }, { expireAfterSeconds: 0 });
//Access the database my_database via mongoose.model.
//The first argument: The name of the collection the model is for.
//Apply the model to the collection?
const PostsAmountsTimeframes = mongoose.model('PostsAmountsTimeframes', PostsAmountsTimeframesSchema)
//Export User variable to other files
module.exports = PostsAmountsTimeframes

使用它来创建条目。我在当前日期后 3 分钟使收集过期。

  var d = new Date()
  d.setMinutes(d.getMinutes()+3);
  var r = new Date(d)

    PostsAmountsTimeframes.create({
      userid: req.session.userId,
      posts_amounts_timeframe: req.session.posts_amounts_timeframe,
      expireAt: r
    }, (error, postsamountstimeframes) => {
      console.log(error)
    })
  • 关闭 mongosh
  • 关闭 Mongo Compass
  • 重建项目
  • 重新运行项目
  • 创建一个条目,然后砰!创建后它会自动删除自己 一个条目。

应该有一种方法可以对 TTL 过期做同样的事情。目前正在研究该方法!

关于node.js - Mongoose Schema 设置过期字段来删除文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71273672/

相关文章:

c++ - 从 Node JS 访问用 C++ 编写的设备 SDK

具有文档字段比较的 MongoDB partialFilterExpression

node.js - 如何在 Nodejs 中为 MongoDB 官方文档中提到的每条评论创建唯一的 Slug?

mongodb - 如何在 mongodb 中使用 $regex?

javascript - ExpressJS - 不会将新用户发布到 MongoDB(500 内部服务器错误)

javascript - 哪些内置模块负责 Node.js 中的系统调用?

node.js - 如何读取 Angular-4 Assets 中的 csv 文件

node.js - nodejs , mongo find 返回无数据

javascript - 如何使用 for Each 在 json 中添加特定值

c# - 使用 C# 在 MongoDB 中使用 IsoDate 和 DateTime