【问题标题】:mongoose TTL partialFilterExpression not working?猫鼬 TTL partialFilterExpression 不起作用?
【发布时间】:2022-01-05 12:00:48
【问题描述】:

我正在使用mongoose 创建一个用户模型。我正在尝试用partialFilterExpression 实现ttl indexing。但它不起作用..

这是我的代码-

const { Schema, model } = require("mongoose");

const userSchema = new Schema({
    name: String,
    firstName: {
        type: String,
        required: [true, 'Firstname is required'],
    },
    lastName: {
        type: String,
        required: [true, 'Lastname is required'],
    },
    email: {
        type: String,
        required: true,
    },
    phone: String,
    password: {
        type: String,
        select: false
    },
    avatar: String,
    provider: String,
    googleId: String,
    facebookId: String,
    verified: {
        type: Boolean,
        default: false
    },
    address: String,
    country: String,
    city: String,
    zipCode: String,
    role: {
        type: String,
        enum: ['user', 'seller', 'admin', 'superAdmin'],
        default: 'user'
    }
}, { timestams: true });

userSchema.index({ createdAt: 1 }, {
    expireAfterSeconds: 300,
    partialFilterExpression: {
        verified: false
    }
});

module.exports.User = model('User', userSchema);

在这里,我想在 5 分钟后在验证为假时删除此数据....我错在哪里或如何使用 mongoose 做到这一点。

【问题讨论】:

  • 除了架构timestams中的拼写错误之外,是否在数据库中创建了索引?
  • 您需要在架构中定义 createdAt 字段,并且您需要在文档创建时使用时间戳填充它...
  • @Joe,不是没有创建索引。我添加了timestamps。现在它添加createdAtupdatedAt。但不会删除它。
  • 当我测试该代码时,它会在设置了过期时间的用户集合上创建一个索引,并在 6 分钟后删除具有“createdAt”字段的文档。

标签: node.js mongodb express mongoose


【解决方案1】:

您的写作有一些拼写错误。它将是timestamps: true。它现在应该可以工作了..

【讨论】:

  • 不工作..请帮助我
  • 对于带有 Mongoose 的 NestJs,使用这个:@Schema({timestamps: true})
  • 不是nestjs..我用的是expressjs
  • 没人能清除吗?请帮帮我
猜你喜欢
  • 1970-01-01
  • 2014-04-23
  • 2019-12-17
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 2014-12-19
  • 2015-11-16
相关资源
最近更新 更多