更新了 Loopback 中行为不一致的相关对象

Updated related objects in Loopback behaving inconsisently

更新相关对象时,同一代码出现两种完全不同的行为。例如,一个问题属于一个学生。我 运行 下面的代码在两台不同的机器上。

Question.observe('after save', function (ctx, next) {

   var question = ctx.instance

   question.student(function (err, student) {
      student.updateAttributes({points: student.points - question.points})
   })

next();

})

在第一台机器上它运行完美。所以我以为我完成了。但是当我 运行 在另一台机器上使用完全相同的代码时,我收到以下错误:

  student.updateAttributes({points: student.points - question.points})
                                           ^
  TypeError: Cannot read property 'points' of null

我正在使用内存连接器

  "db": {
     "name": "db",
     "connector": "memory",
   }

我唯一想到的是我有两个不同版本的环回(一个有错误,另一个没有)......但是 package.json 两者也完全相同! ?

{
  "name": "foo",
  "version": "1.0.0",
  "main": "server/server.js",
  "scripts": {
    "start": "node .",
    "pretest": "jshint .",
    "test": "mocha"

  },
  "dependencies": {
    "compression": "^1.0.3",
    "cors": "^2.5.2",
    "loopback": "^2.22.0",
    "loopback-boot": "^2.6.5",
    "loopback-component-explorer": "^2.1.0",
    "loopback-datasource-juggler": "^2.39.0",
    "serve-favicon": "^2.0.1"
  },
  "devDependencies": {
    "chakram": "^1.2.1",
    "jshint": "^2.8.0",
    "loopback-testing": "^1.2.0",
    "mocha": "^2.3.4",
    "mocha-bamboo-reporter": "^1.1.0"
  },
  "repository": {
    "type": "",
    "url": ""
  },
  "description": "foo"
}

你的 packages.json 指定一个包应该高于设定的版本,所以你可以有一台机器 loopback 的版本是 v2.23.0 而另一台机器是 v2.26.2(当前最新的),如果你 运行 npm install 在不同的时间。

您可以 运行 npm list 在两台机器上比较安装的版本。

运行 npm update 更新包。

要更新您的 package.json 以使用最新的依赖项,请查看此 answer

您没有检查 question.student 中的错误。所以首先你需要解决这个问题。

然后,可能不完全相关,但 question.student 很可能是异步的,因此您在 question.student 完成之前调用 next

更好的代码应该是这样的

Question.observe('after save', function (ctx, next) {

   var question = ctx.instance

   question.student(function (err, student) {
     if (err) return next(err);
       
     student.updateAttributes({points: student.points - question.points})
         
     next();
   });
});

此外,我对 updateAttributes 一无所知,但如果它是异步的,你也只需要在它完成后调用 next()(使用你为 question.student 例如),并检查错误。

总是检查错误。这不仅仅是一个好习惯。