mongodb - 模型中的 Sails.js expireAfterSeconds 选项

标签 mongodb model sails.js database

我正在使用 sails 编写一个简单的模型,它会在几个小时后过期,所以我需要类似的东西

    createdAt: {
        type: 'Date',
        expires : 60,
        index: true
    }

但是当我检查我的数据库(MongoDB)时,“expireAfterSeconds”似乎不起作用,因此我必须使用

db.collection.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

我想知道是否可以在模型中设置“过期”选项?

最佳答案

检查负责处理 index 属性属性的 sails-mongo 源代码[1],它似乎没有考虑像 expires 这样的事情属性(property)。不过这是有道理的,因为 sails.js 水线 ORM 不支持特定于数据库的功能,例如 MongoDB 中的过期索引数据。

但是,waterline 确实通过 Collection.native() 方法 [2]

提供对 MongoDB native 连接(使用 node-mongodb-native )的访问

很有可能,在 Sails 应用程序的生命周期中,您真的只需要对模型的索引进行一次更改,因此最好的地方是在 config/bootstrap.js 文件中.在 sails.js 生命周期的这一点上,所有模型都已实例化,因此您可以执行类似这样的操作来对您的键执行必要的逻辑:

// config/bootstrap.js
exports.bootstrap = function (done) {

    YourModelName.native(function (err, collection) {
        // define index properties
        collection.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } );

        // be sure to call the bootstrap callback to indicate completion
        done();
    });
}

您可以更进一步,编写一个实用程序来检查 sails 已加载的模型(它们可用作全局对象 sails.models 中的键),如果它们有一个 expires 属性,执行必要的 native 功能。这也需要在 config/bootstrap.js 中完成。

如果您有需要在每条记录的基础上完成的 native 功能,您可以为此使用 sails.js 模型生命周期 Hook [3]。

引用资料:

关于mongodb - 模型中的 Sails.js expireAfterSeconds 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21367333/

相关文章:

node.js - 处理插入中的日期,mongodb

php - 在 MongoDB GridFS 中存储图像

ruby-on-rails - 福雷姆 gem : how to link a forum to other models

mysql - 具有多个来源的 Rails 模型概念

ruby-on-rails - 在 Rails 中访问模型属性

mongodb - Mongo 聚合 $and in $match 未返回结果

javascript - 提高 MongoDB 文本搜索性能

mysql - 创建记录 : should be a number (instead of "xx", 时出现 Sails.js 验证错误,这是一个字符串)

javascript - SailsJs - 将 html View 导出为 PDF

mysql - 如何使用 unix 套接字(mamp)而不是用于 sails js db 连接的端口?