strongloop 在 afterRemote 方法中创建相关模型对象

strongloop creating related model object in afterRemote method

假设我有一个游戏场景。

一个游戏属于一个用户。

game.json:

{
  "name": "game",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "beer_points_required": {
      "type": "number",
      "required": true
    },
    "total_points": {
      "type": "number",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "game_blngs_to_user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": ""
    }
  },
  "acls": [],
  "methods": []
}

user.json:

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {
    "last_game": {
      "type": "date",
      "required": false
    },
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}

我试图在通过 CRUD 创建用户后以编程方式为用户创建游戏对象,因此在 user.js 中我有:

var config = require('../../server/config.json');
var path = require('path');
var app = require('../app');

module.exports = function(user) {

user.afterRemote('create', function(context, user) {
    console.log('> user.afterRemote triggered');

  //create a game for each user thats created
  var Game = app.models.game;
  game.create({game_blngs_to_userId: user.id, beer_points_required: 0, total_points: 0},function(err, res){
 if(err){
      console.log('\n\n>>err');
      console.log(err);
      next(err);
      return;
    }
    console.log(res);
  });
});

但是,这显然行不通,哈哈,所以我想知道如何真正实现我的目标。我已经盯着强循环文档看了很长时间了,似乎他们 api 的实际用法并没有很好的记录……至少在我看来是这样。谁能帮我解释一下这个?

我认为您的用户引用未定义...尝试:

app.models.user.afterRemote

也许,您缺少第三个参数 - next afterRemote 回调中的函数。

user.afterRemote('create', function(context, user, next) {
  ...
  var Game = app.models.game;
  game.create({game_blngs_to_userId: user.id, beer_points_required: 0, total_points: 0},function(err, res){
 if(err){
      console.log(err);
      next(err);
      return;
    }
    next() // countinue execution
  });
});