如何在保存前删除 属性

How to remove a property before save

我正在使用 Angular 在后端构建我的前端和环回,我的模型有一个关系 HasManyThrough

// person.json
{
  "name": "Person",
  ...,
  "relations": {
    "contacts": {
      "type": "hasMany",
      "model": "Person",
      "foreignKey": "fromId",
      "through": "PersonConnect"
    }
  }
}
// person-connect.json
{
  "name": "PersonConnect",
  "base": "PersistedModel",
  "properties": ...,
  "relations": {
    "from": {
      "type": "belongsTo",
      "model": "Person",
      "foreignKey": "fromId"
    },
    "to": {
      "type": "belongsTo",
      "model": "Person",
      "foreignKey": "toId"
    }
  }
}

如果我尝试使用资源管理器,我可以使用

在两个人之间建立新的关系
PUT /api/Person/:id/contacts/:fk

其中 id、fromId 和 fk 是 toId,问题是 Angular SDK 生成服务还发送正文参数 id 和 fk,这会产生问题,因为设置 PersonConnect.id 相等到 Person.fromId 并附加一个额外的值 fk

{
    "_id" : ObjectId("55f0915f19c46e06675d056e"),
    ...
    "fromId" : ObjectId("55f0915f19c46e06675d056e"),
    "toId" : ObjectId("55f09b4d4d06f8c872e43c84"),
    "fk" : "55f09b4d4d06f8c872e43c84"
}

为了修复我写了以下内容

// person-connect.js
var _ = require('lodash');

module.exports = function (PersonConnect) {
  PersonConnect.observe('before save', function (ctx, next) {
    if (ctx.instance) {
      ctx.instance = _.omit(ctx.instance, ['id', 'fk']);
    }

    next();
  });
};

没有成功,id 和 fk 值仍在使用发送值,我设置为 null 并工作但我得到类似

{
    "_id" : ObjectId("55f18c67bbfa11053b36cafc"),
    ...
    "fromId" : ObjectId("55f0915f19c46e06675d056e"),
    "toId" : ObjectId("55f09b4d4d06f8c872e43c84"),
    "fk" : null
}

如何在回送中存储模型之前删除属性?

您可以尝试改用 unsetAttribute:

ctx.instance.unsetAttribute('unwantedField');