首页 > 解决方案 > Sails v1 不再支持模型实例方法

问题描述

我不断收到错误消息“在customToJSON模型的属性中user:Sails v1 不再支持模型实例方法。请将此实例方法中的逻辑重构为静态方法、模型方法或帮助程序。”。我是 node.js 的新手,不知道该怎么做。

我的用户.js

const bcrypt = require("bcrypt")
const Promise = require("bluebird")

module.exports = {
  attributes: {
    firstName: {
      type: "string",
      required: true
    },
    lastName: {
      type: "string",
      required: true
    },
    username: {
      type: "string",
      required: true,
      unique: true
    },
    email: {
      type: "email",
      required: true,
      unique: true
    },
    password:{
      type: "string",
      minLength: 6,
      required: true,
      columnName: "encryptedPassword"
    },  
    customToJSON: function(){
        const obj = this.toObject()
        delete obj.password
    }
    }
};

标签: node.jssails.js

解决方案


首先,我希望您喜欢使用 Node 和 Sails 进行开发。

现在要解决您的问题,我猜您正在使用基于sails v0.12 的指南或教程,但就像错误消息所说的那样,实例方法已从v1.0 开始从Sails 和Waterline 中删除。

话虽如此,解决方案非常简单,将您的 customToJSON 方法移出模型的属性部分。这基本上允许sails v1找到它。

所以你的模型看起来像这样

...
attributes: {
    ...
    ,
    password:{
      type: "string",
      minLength: 6,
      required: true,
      columnName: "encryptedPassword"
    },
},

customToJSON: function() {
    return _.omit(this, ['password']); 
},
...

有关sails 中customToJSON 的更多信息,请参见此处,有关替换实例方法的更多信息,请参见此处


推荐阅读