【问题标题】:Express : TypeError: user.company.pull is not a functionExpress : TypeError: user.company.pull 不是函数
【发布时间】:2018-10-04 05:02:15
【问题描述】:

我想从我的用户对象中删除一个对象元素,我正在使用 pull 来删除它,但它返回了

TypeError: user.company.pull 不是函数

router.put('/reset', passport.authenticate('jwt', {session:false}), (req, res, next)=> {
    user = req.user;
    var id_student = user.id;
    var id_company = user.company;
    var results = [];
    User.findById(id_student, function(err, user) {
        if(err) {
            console.log(err);
            return res.status(500).send({message: "Error"});
        }
        if(!user) {
            return res.status(404).send({message: "User Not Found"});            
        }
        user.company.pull({'company': id_company});
        res.send(user);
    });
});

【问题讨论】:

  • 你忘了var使用"use strict"
  • 我可以把它放在哪里?

标签: javascript node.js express mongoose mean


【解决方案1】:

js 文件的顶部使用'use strict';

阅读https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode了解更多信息

检查变量user是否有属性copmany并处理。

使用这个条件

if(!user || !user.hasOwnProperty('company')) {
    return res.status(404).send({message: "User Not Found"});            
}

【讨论】:

  • 我不认为这是当前的问题。第 2 行的 user 定义将在代码到达 User.findById 时超出范围,因为回调中定义了 user 参数。
  • 所以只是第二行的答案是错误的,对吧? @JoshMcMillan
  • 但它给了我 TypeError: Cannot read property 'pull' of null
  • user 是否有属性company?你查过??在调用pull之前登录user
【解决方案2】:

实际上,user.company.pull 可能是未定义的,而不是您要查找的函数。

如果user.company 不存在,那么user.company 将是undefined,并且在undefined 上没有定义pull 方法。这意味着您实际上是在尝试调用undefined.pull({'company': whatever}),这将永远无法工作。

尝试添加警卫以确保您有公司与用户关联,就像您检查以确保用户存在一样。例如:

if (!user.company) {
    return res.status(404).send({ message: 'Company not found'});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-07
    • 2019-11-03
    • 1970-01-01
    • 2019-08-13
    • 2018-08-22
    • 2020-06-29
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多