删除MongoDB索引和缓存问题

由于数据模型是拷贝的,忘记删除原来的索引,导致存入数据时MongoDB抛异常exceptionHandler { MongoError: E11000 duplicate key error collection: house_eva.wpestatecomprehensivenesses index: real_estate_name_1_city_1 dup key: { real_estate_name: "胜利苑", city: null }

第一步:我删除模型的索引代码:// 创建复合唯一索引 WpEstateComprehensivenessSchema.index({ real_estate_name: 1, city: 1 }, { unique: true });上传代码。

第二步:删除所有索引,删除所有记录,查找所有索引并立即插入数据仍旧报相同的错误。

注意:MongoDB的索引可以删除。MongoDB没有具体的删除表的语句,MongoDB的删除表就实际相当于删除该表的所有记录,当然需要把后台的表模型代码删除。

javascript 复制代码
    // 删除索引
    WpEstateComprehensiveness.collection.dropIndex('real_estate_name_1_city_1', function(err) {
        if (err) {
            console.log('Error dropping index:', err);
        } else {
            console.log('Index successfully dropped!');
        }
    });
    // 删除 real_estate_name 为 "胜利苑" 的所有记录
    WpEstateComprehensiveness.deleteMany({ real_estate_name: '胜利苑' }, function(err) {
        if (err) {
            console.log('Error deleting documents:', err);
        } else {
            console.log('Documents successfully deleted!');
        }
    });
    WpEstateComprehensiveness.find({
        real_estate_name: '胜利苑',
        city: null
    }, function(err, duplicates) {
        if (err) {
            console.error('Error finding duplicates:', err);
        } else {
            console.log('Duplicates found:', duplicates);
            // Decide what to do with the duplicates (remove, update, etc.)
        }
    });
    // 获取所有索引信息
    WpEstateComprehensiveness.collection.indexInformation(function(err, indexes) {
        if (err) {
            console.log('Error getting index information:', err);
        } else {
            console.log('Indexes for WpEstateComprehensiveness:', indexes);
        }
    });

问题出在哪里呢?最后通过尝试,一步一步来,发现是换存问题。

解决步骤是:

第一次调用接口只删除索引。

第二次调用接口插入新数据。

千万不能两个一起使用,不然因为缓存问题导致删除索引失败的。

相关推荐
21号 18 分钟前
4.客户端(Redis)
开发语言·数据库·github
云和数据.ChenGuang14 分钟前
MongoDB 提供的 `GridFSTemplate` 操作 GridFS 大文件系统的常用查询方式
数据库·mongodb
一只自律的鸡1 小时前
【MySQL】第四章 排序和分页
数据库·mysql
qq_203769492 小时前
debian13安装PostgreSQL并远程连接
数据库·postgresql
苏小瀚2 小时前
[MySQL] 联合查询
数据库·mysql
雪碧聊技术2 小时前
Linux命令过关挑战
linux·运维·数据库
oak隔壁找我2 小时前
SpringBoot + MyBatis 配置详解
java·数据库·后端
oak隔壁找我2 小时前
SpringBoot + Redis 配置详解
java·数据库·后端
帧栈2 小时前
开发避坑指南(64):修复IllegalArgumentException:参数值类型与期望类型不匹配
java·数据库
麦聪聊数据2 小时前
Web原生架构如何优化数据库权限管理:简化操作与增强安全性
数据库