gpt4 book ai didi

node.js - MongoDB TTL 意外过期时间

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:43 25 4
gpt4 key购买 nike

我尝试创建一条记录,其架构将在设置时间后删除,但无论我设置多长时间,它总是会在 1-2 分钟后删除。

我尝试按照官方mongoDb TTL文档和其他文章进行操作,但没有达到预期效果

const mongoose = require('mongoose');
const moment = require('moment');


const UserSchema = new mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
password:{
type: String,
required: true
},
token:{
type: String,
},
emailVery:{
type: Boolean,
default: false
},
createdAt:{
type: Date,
required: true,
default: Date.now
}
});

UserSchema.index({ createdAt: 1 }, { expireAfterSeconds : 3600 });


const User = mongoose.model('User', UserSchema);

module.exports = User;

它也有一个错误: Node :20228)DeprecationWarning:collection.ensureIndex 已弃用。请改用 createIndexes。虽然我从不在代码中的任何地方使用 collection.ensureIndex。

最佳答案

从你的语法来看,你似乎使用的是 mongoose 3.X 版本,并且 MongoDB 高于 3.0

您应该更新您的 Mongoose 版本,然后使用索引功能。

Mongoose :

以下是 mongoose 5.X 版本的语法:

var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
s.path('my.date').index({ expires: 60 });

.index will call createIndex of mongoDB.

<小时/>

MongoDB

Deprecated since version 3.0.0: db.collection.ensureIndex() is now an alias for db.collection.createIndex().

UserSchema.createIndex({ "createdAt": 1 }, { expireAfterSeconds : 3600 });

也许,expireAfterSeconds 应该可以正常工作。

希望这有帮助!

关于node.js - MongoDB TTL 意外过期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com