模型中的Sails.js expireAfterSeconds选项

时间:2014-01-26 18:18:45

标签: mongodb model sails.js database

我正在使用帆来编写一个简单的模型,该模型应该在几个小时后过期,所以我需要像

这样的东西
    createdAt: {
        type: 'Date',
        expires : 60,
        index: true
    }

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

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

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

2 个答案:

答案 0 :(得分:3)

检查负责处理index属性[1]的sails-mongo源代码,似乎没有考虑expires属性之类的内容。这是有道理的,因为sails.js waterline ORM不支持特定于数据库的功能,例如MongoDB中的索引数据到期。

但是,waterline确实通过Collection.native()方法提供对MongoDB本机连接(使用node-mongodb-native)的访问权限[2]

很可能,您只需要在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.models中可用作键),如果它们具有expires属性,执行必要的本机功能。这也需要在config/bootstrap.js中完成。

如果你需要在每个记录的基础上完成本机功能,你可以使用sails.js模型生命周期钩子[3]。

的引用:

答案 1 :(得分:0)

更新: 我创建了一个sails钩子,为使用sails-mongo适配器的模型提供高级索引选项。

支持所有mongo索引选项。

https://www.npmjs.com/package/sails-hook-mongoat

OLD:

如果model属性具有expires属性且类型为'date',则我创建了以下内容以自动执行此操作。只需粘贴到config / bootstrap.js

即可

希望它有所帮助!

  _.forEach(Object.keys(sails.models), function(key) {
    var model = sails.models[key];
    _.forEach(Object.keys(model.attributes), function(attr) {
      if (model.attributes[attr].hasOwnProperty('expires')) {
        var seconds = model.attributes[attr].expires;
        // delete validators from global model, otherwise sails will error
        delete sails.models[key].attributes[attr].expires;
        delete sails.models[key]._validator.validations[attr].expires;
        if (model.attributes[attr].hasOwnProperty('type') && model.attributes[attr].type === 'date') {
          var obj = {};
          obj[attr] = 1;
          model.native(function(err, collection) {
            // define index properties
            collection.ensureIndex(obj, {
              expireAfterSeconds: seconds
            }, function(err) {
              if (err)
                sails.log.error(err);
              else
                sails.log.info(key + " model attribute '" + attr + "' has been set to expire the document after " + seconds + " seconds.");
            });
          });
        } else {
          sails.log.warn(key + " model attribute '" + attr + "' is set to expire but is not of type 'date'. Skipping...");
        }
      }
    });
  });