MongoDB数据自动删除求助:未设置TTL但数据定期消失
问题:Mongoose写入MongoDB的数据自动消失(未设置TTL)
我通过Mongoose向MongoDB写入数据,但数据会在一段时间后自动删除,我不想让数据丢失。在Windows服务器的MongoDB Compass里也能观察到这个现象,而且没有设置任何TTL索引。
相关代码
主文件代码:
const mongoose = require('mongoose'); const { mongoURI, databaseName } = require('./config'); // 获取连接信息 const Keyword = require('./schema'); // 导入Schema模型 // MongoDB连接 mongoose.connect(`${mongoURI}/${databaseName}`, { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => { console.log(`Connected to database: ${databaseName}`); }).catch((err) => { console.error('Database connection error:', err); process.exit(1); // 出错时终止进程 }); // 添加新关键词 const newKeywordName = "example_keywordxxx"; const newKeywordData = { keyword_name: newKeywordName, keyword_process_server: "server_1", }; // 直接在代码中检查并添加 Keyword.exists({ keyword_name: newKeywordName }) .then((exists) => { if (exists) { console.log(`Keyword "${newKeywordName}" already exists.`); } else { const newKeyword = new Keyword(newKeywordData); return newKeyword.save() .then(() => console.log('Keyword saved successfully')); } }) .then(() => { console.log('Closing the database connection...'); return mongoose.disconnect(); // 操作完成后断开连接 }) .catch((err) => { console.error('Error:', err); mongoose.disconnect(); // 出错时断开连接 }) .finally(() => { console.log('Process finished.'); process.exit(0); // 完全终止进程 });
schema.js代码:
const mongoose = require('mongoose'); const keywordSchema = new mongoose.Schema({ keyword_name: { type: String, unique: true, required: true, index: true }, // keyword_name唯一、必填且带索引 keyword_process_server: { type: String, required: true, default: "default_server" }, keyword_is_available: { type: Boolean, default: true }, keyword_is_success: { type: Boolean, default: false }, keyword_add_time: { type: Date, default: Date.now }, keyword_finish_time: { type: Date, default: null }, }); // 导出模型 module.exports = mongoose.model('Keyword', keywordSchema);
可能的原因及解决办法
1. 检查MongoDB存储配置与权限
- 确认MongoDB使用持久化存储引擎:打开MongoDB配置文件(
mongod.cfg),查看storage.engine配置,确保值为wiredTiger(默认),而非内存型引擎。 - 检查数据目录权限:Windows服务器上,MongoDB服务的运行账户需要对配置中
storage.dbPath指定的目录有读写权限,否则数据无法持久化,重启服务后会丢失。 - 查看MongoDB日志:在配置的
logPath目录下找到日志文件,搜索是否有写入失败、数据目录异常的报错信息。
2. 排查是否存在误操作
- 检查是否有其他脚本、定时任务或服务在操作同一数据库/集合,执行了删除数据的动作。可以开启MongoDB审计日志,或者通过
db.getCollection('system.profile').find()(需开启数据库 profiling)追踪数据变更记录。 - 确认连接的数据库是否正确:检查代码中
databaseName的值,确保写入的是预期的数据库,而非临时测试库。
3. 优化代码写入逻辑
- 确保写入操作完成持久化:修改
save()方法,添加写入确认参数,保证数据写入磁盘:
return newKeyword.save({ writeConcern: { w: 'majority' } }) .then(() => console.log('Keyword saved successfully'));
- 排查重复执行逻辑:确认是否有定时任务重复运行这段代码,虽然有
exists检查,但如果有其他操作修改了keyword_name的唯一性约束,可能引发意外情况。
4. 验证Compass显示是否准确
- 确认Compass连接的是服务器上的MongoDB实例,而非本地测试实例。
- 刷新Compass的集合视图,排除缓存导致的显示错误。
内容的提问来源于stack exchange,提问作者Sakulta Salkım
相关产品推荐
相关产品推荐

