时间住在mongodb,猫鼬不工作.文件不会被删除 [英] Time to live in mongodb, mongoose dont work. Documents doesnt get deleted

查看:52
本文介绍了时间住在mongodb,猫鼬不工作.文件不会被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的node.js应用中使用此方案进行会话

Im using this scheme for a session in my node.js app

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);

然后我在应用中使用以下方法创建会话":

And I create a "session" in my app with:

...
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设置为:字符串为数字,即15,为字符串"15s",依此类推.

The problem is that the document lives permanetly, its never expires. It should only live for 15 seconds (up to a minute). Whats wrong with my code? I have tried to set the expries: string to a number i.e 15, to a string '15s' and so on.

推荐答案

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秒长一点.

A TTL index deletes a document 'x' seconds after its value (which should be a Date or an array of Dates) has passed. The TTL is checked every minute, so it may live a little longer than your given 15 seconds.

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

To give the date a default value, you can use the default option in Mongoose. It accepts a function. In this case, Date() returns the current timestamp. This will set the date to the current time once.

您也可以选择以下路线:

You could also go this route:

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

这会每次调用.save()而不是.update()时更新每次的值.

This will update the value every time you call .save() (but not .update()).

这篇关于时间住在mongodb,猫鼬不工作.文件不会被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆