首页 > 解决方案 > 为什么猫鼬TTL删除文档,即使部分过滤器与选项不匹配

问题描述

我的部分过滤器正在删除文档,但用户不符合该要求,我是否错误地使用了部分过滤器?

谢谢


const postSchema = new mongoose.Schema(
    {
        title: { type: String },
        description: { type: String },
        image: { type: String },
        price: { type: String },
        location: { type: String },
        image: { type: Array },
        author: {
            type: String,
            ref: 'User'
        },
        authorPremium: {
            type: Boolean,
            default: true,
            index:true
        },
        reported: {
            type: Boolean,
            default: false
        },
        reportClear: {
            type: Boolean,
            default: false
        }
    },
    {
        timestamps: true
    }
);

// users who are not premium will have posts deleted after 20 seconds
postSchema.index({ createdAt: 1 }, { expireAfterSeconds: 20, partialFilterExpression: { authorPremium: false } });

module.exports = mongoose.model('Post', postSchema);

部分文件管理器不应允许删除为 true 的 authorPremium,但只有 delete 是 authorPremium 为 false ...请告知。

从 mongo 索引返回

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.posts"
        },
        {
                "v" : 2,
                "key" : {
                        "createdAt" : 1
                },
                "name" : "createdAt_1",
                "ns" : "test.posts",
                "expireAfterSeconds" : 120,
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "authorPremium" : 1
                },
                "name" : "authorPremium_1",
                "ns" : "test.posts",
                "background" : true
        },
        {
                "v" : 2,
                "key" : {
                        "timestamps" : 1
                },
                "name" : "timestamps_1",
                "ns" : "test.posts",
                "expireAfterSeconds" : 20,
                "background" : true
        }
]

似乎当我使用 mongo cmd 时,我的一些旧设置仍然存在..还有一些新设置?那么如何在测试时完全清除这些旧的 ttl 设置并确保只有我想要的那些?

标签: javascriptmongodbmongoosemongodb-querymongoose-schema

解决方案


看起来您.index(...)不起作用,因为您已经在createdAt字段上有旧索引并且猫鼬不会丢弃旧索引。要将索引与您的架构同步,您可以使用Model.syncIndexes

更多关于.index()工作原理和.syncIndexes()引入原因的信息可以在这里找到。


推荐阅读