node.js - 在 SailsJS 中维护模型更新历史

标签 node.js mongodb mongoose sails.js sails-mongo

在 Sails 中维护模型数据历史的有效方法是什么?例如,如果用户更新数据库,我们如何维护数据,我们希望保留版本以在数据更新时恢复数据。

我见过许多使用“更改”标签的示例,该标签将日期保留为子标签。这是最有效的吗?

在模型更新时,我们可以复制以前的信息。是否有更好的建议或示例链接?

{
   text:"This is the latest paragraph",
   changes:{
      text:{
          "1470685677694":"This was the paragraph",
          "1470685577694":"This was the original paragraph"
      }
   }
}

我希望找到一个好的解决方案来查找/搜索和优化这些数据,以允许用户在必要时恢复。

最佳答案

您可以像下面这样定义您的模型,这样您就可以保留历史记录,您可以使用它来恢复任何以前的值。

api/models/Test.js

module.exports = {
  connectionName:"someMongodbServer",
  tableName:"test",
  autoCreatedAt:false,
  autoUpdatedAt:false,
  autoPk:false,
  attributes: {
    id:{
      type:"integer",
      primaryKey:true,
      autoIncrement:true
    },
    name:"string",
    history:{
      type:'json',
      defaultsTo:[]
    }
  },
  beforeCreate:function(value,cb){
    Test.count().exec(function (err, cnt) {
      if(err)
        return cb(err);
      value.id = cnt + 1;
      cb();
    });
  },
  beforeUpdate:function(values,cb){
    Test.native(function(err,collection){
      if(err)
        return cb(err);
      collection.findOne({_id:values.id},{history:0,_id:0},function(err,data){
        if(err)
          return cb(err);
        collection.updateOne({_id:values.id},{$push:{history:data}},function(err,res){
          if(err)
            return cb(err);
          console.log(res);
          cb();
        });
      })
    });
  }
};

关于node.js - 在 SailsJS 中维护模型更新历史,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38837442/

相关文章:

javascript - 如何从mongodb中选择一个字段不等于某一值的所有文档

node.js - 我应该集中数据库连接还是为每个集群创建新连接?

node.js - 如何使用 Node、Async 和 Mongoose 计算作用域变量的总和?

javascript - Express 和 Passport Js - Google OAuth 2.0 策略没有给我 req.user 对象

mongodb - Golang MongoDB在列表上使用$ in运算符-结果参数必须是 slice 地址

python - Mongoengine-类型错误: Instantiating a document with positional arguments is not supported

javascript - MongoDB 通过查找查询随机选择 5 个文档

javascript - Mongoose - 查询 exec() 永远不会在模型方法中解析

javascript - Array.push(Object) 插入对象数组

javascript - 为什么我的错误没有在我的快速回复中返回?