gpt4 book ai didi

node.js - 时间住mongodb,mongoose不行。文档不会被删除

转载 作者:可可西里 更新时间:2023-11-01 09:23:12 27 4
gpt4 key购买 nike

我在我的 node.js 应用程序中使用这个方案进行 session

var mongoose     = require('mongoose');
var Schema = mongoose.Schema;
// define the schema for our user session model
var UserSessionSchema = new Schema({
sessionActivity: { type: Date, expires: '15s' }, // Expire after 15 s
user_token: { type: String, required: true }
});
module.exports = mongoose.model('UserSession', UserSessionSchema);

然后我在我的应用程序中创建了一个“ session ”:

...
var session = new Session();
session.user_token = profile.token;
session.save(function(save_err) {
if (save_err) {
....
} else {
// store session id in profile
profile.session_key = session._id;
profile.save(function(save_err, profile) {
if (save_err) {
...
} else {
res.json({ status: 'OK', session_id: profile.session_id });
}
});
...

问题是文件是永久存在的,它永远不会过期。它应该只存在 15 秒(最多一分钟)。我的代码有什么问题?我尝试将 expries: string 设置为数字,即 15,设置为字符串 '15s' 等等。

最佳答案

var UserSessionSchema   = new Schema({
sessionActivity: { type: Date, expires: '15s', default: Date.now }, // Expire after 15 s
user_token: { type: String, required: true }
});

TTL 索引会在其值(应该是日期或日期数组)过去 'x' 秒后删除文档。 TTL 每分钟检查一次,因此它可能会比您给定的 15 秒长一点。

要为日期提供默认值,您可以使用 Mongoose 中的 default 选项。它接受一个函数。在这种情况下,Date() 返回当前时间戳。这会将日期设置为当前时间一次

你也可以走这条路:

UserSessionSchema.pre("save", function(next) { 
this.sessionActivity = new Date();
next();
});

这将每次您调用.save()(但不是.update())时更新值。

关于node.js - 时间住mongodb,mongoose不行。文档不会被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24008956/

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