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

时间:2015-01-20 08:06:27

标签: node.js loopbackjs strongloop

说我有游戏场景。

游戏属于用户。

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的实际用法并没有那么详细记录......至少在我看来。有谁能请我为此透露一下?

2 个答案:

答案 0 :(得分:3)

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

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
  });
}); 

答案 1 :(得分:0)

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

app.models.user.afterRemote