sequelize toJSON 的自定义序列化

custom serialisation of sequelize toJSON

目前 sequelize 会像这样序列化一个实例

 id: 2,
  title: 'bla bla',
  url: 'https://mail.google.com/mail/u/0/#inbox/14c6002a21ae0679',
  createdAt: Sat Mar 28 2015 18:58:42 GMT+0800 (SGT),
  updatedAt: Sat Mar 28 2015 18:58:42 GMT+0800 (SGT),
  userBookmarks:
   { createdAt: Sat Mar 28 2015 18:59:16 GMT+0800 (SGT),
     updatedAt: Sat Mar 28 2015 18:59:16 GMT+0800 (SGT),
     userId: 1,
     bookmarkId: 2 } }

我只想强调关系序列化的方式。这是一个书签模型,想要构建或使用一个库,该库通常将 userbookmarks xxx 的关系修改为 user:[];

有什么想法吗?

您可以提供自定义 toJSON 函数:

var model = sequelize.define(name, attributes, {
    instanceMethods: {
        toJSON: function () {
            var values = this.constructor.prototype.toJSON.call(this); 
            // Do your magic here 
        }
    } 
});