node.js - "TypeError: Cannot read property ' 为多个请求推送 ' of null"

标签 node.js postgresql angular express sequelize.js

我正在构建一个 Angular Node 应用程序评级系统。在该系统中,我试图遍历作为 POST 请求发送到服务器的一组 id,并使用 for 循环将这些 id 推送到用户需要评分的列中。

第一个用户成功推送了整个循环,但下一个用户在第二个索引处失败。调试后,我发现后端正在接收所有正确的变量,我不明白为什么它不适用于用户 2 但适用于用户 1。

这是我的后端代码

 addRatee: function addRatee(req,res) {
    var decoded = jwt.decode(req.query.token);
    return model.User.findById(req.params.raterId)
      .then(function (user) {
      for (let ratee of req.body.rateeIds) {
        user.needToRate.push(ratee);
      }
      user.update({
        needToRate: user.needToRate
      }).then(function (updatedUser) {
        return res.status(200).json({
          title: "Successfully added users to need to rate",
          obj: updatedUser
        });
      }).catch(function () {
        return res.status(400).json({
          message: "Error updating user",
          error: err.toString()
        });
      });
    }).catch(function (e) {
      return res.status(400).json({
        message: "Error finding user",
        error: e.toString()
      });
    });
  }

这是我的组件服务代码
 addRatee(rateeIds: number[], raterId: number) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const token = localStorage.getItem('token')
      ? '?token=' + localStorage.getItem('token')
      : '';
    const body = {
      rateeIds: rateeIds
    };
    return this.http.patch(this.devUrl + '/new-ratee/' + raterId + token, body, {headers: headers});
  }

这是我的 component.ts 代码
let dRateeIds = [this.trip.rider1Id, this.trip.rider2Id, this.trip.rider3Id];
              let r1RateeIds = [this.trip.driverId, this.trip.rider2Id, this.trip.rider3Id];
              let r2RateeIds = [this.trip.rider1Id, this.trip.driverId, this.trip.rider3Id];
              let r3RateeIds = [this.trip.rider1Id, this.trip.rider2Id, this.trip.driverId];
                  this.tripService.addRatee(dRateeIds, this.trip.driverId)
                    .subscribe(updatedUser => {
                      console.log(updatedUser);
                      this.tripService.addRatee(r1RateeIds, this.trip.rider1Id)
                        .subscribe(updatedUser2 => {
                          console.log(updatedUser2);
                      this.tripService.addRatee(r2RateeIds, this.trip.rider2Id)
                        .subscribe(updatedUser3 => {
                          console.log(updatedUser3);
                          this.tripService.addRatee(r3RateeIds, this.trip.rider3Id)
                            .subscribe(updatedUser4 => {
                              console.log(updatedUser4);
                            }, resp => console.log(resp));
                        }, resp => console.log(resp));
                    }, resp => console.log(resp));
                }, resp => console.log(resp));

我对编程还很陌生,所以我的代码有点困惑,我只是在寻找发生此错误的原因。

这是给出的完整错误堆栈。
{"message":"Error finding user","error":"TypeError: Cannot read property 'push' of null\n    at /Users/jonathancorrin/Desktop/workspace/atlas-web/server/controllers/trips.js:1380:24\n    at tryCatcher (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/util.js:16:23)\n    at Promise._settlePromiseFromHandler (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/promise.js:512:31)\n    at Promise._settlePromise (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/promise.js:569:18)\n    at Promise._settlePromise0 (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/promise.js:614:10)\n    at Promise._settlePromises (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/promise.js:693:18)\n    at Async._drainQueue (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/async.js:133:16)\n    at Async._drainQueues (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/async.js:143:10)\n    at Immediate.Async.drainQueues (/Users/jonathancorrin/Desktop/workspace/atlas-web/node_modules/bluebird/js/release/async.js:17:14)\n    at runCallback (timers.js:781:20)\n    at tryOnImmediate (timers.js:743:5)\n    at processImmediate [as _immediateCallback] (timers.js:714:5)"}

这是我的 pgadmin 表在几次不成功的尝试后的样子。用户 2-4 的空值

enter image description here

****** 更新
以下是在配置之前记录 needsToRate 列时记录的值和值类型

用户需要评价====== null
用户类型 NTR========== 对象

最佳答案

这个问题是我试图将值插入空字段。我用这段代码解决了这个问题

 for (let ratee of req.body.rateeIds) {
        if (user.needToRate === null) {
          user.needToRate = [];
          user.needToRate.push(ratee)
        } else {
          user.needToRate.push(ratee)
        }
      }

关于node.js - "TypeError: Cannot read property ' 为多个请求推送 ' of null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45826421/

相关文章:

javascript - Object.assign(module.exports, {...}) 与 module.exports = {...}

database - 玩 Scala Slick 交易

javascript - THREE.SpriteCanvasMaterial 不是构造函数 | Angular 7

javascript - node-webkit 如何在另一个窗口中调用一个函数?

javascript - Node/异步 : how to keep my code easy to understand

sql - Postgres 9.4——在向表中插入行时如何忽略重复键

PostgreSQL 在一个查询中更改所有项目(TABLE、SEQ、FUNC、VIEW)GRANT/OWNER

angular - 如果使用 Spring + SockJS + STOMP,websocket 消息会被缓存吗?如果没有,如何检测网络断开?

javascript - 如何使用 [(ngModel)] 双向数据绑定(bind)在 Angular 4 中创建切换开关开关按钮

javascript - SetTimeOut 是 windows 对象(浏览器)的一部分,那么它将如何与 Node js 一起工作