【问题标题】:NodeJS: return getter property of class instance in res.jsonNodeJS:在res.json中返回类实例的getter属性
【发布时间】:2018-11-19 21:45:45
【问题描述】:

在我下面的代码中,

  • 我在我的 Person 类中调用静态“findAllPeople”方法。此方法返回一组 Person 对象。
  • Person 类还有一个用于 fullName 的 getter。

问题: res.json(Array.from(people))返回 Person 对象的数组,但没有 fullName 属性。 当我在 VS Code 中调试 Array.from(people) 时,它会正确返回带有 fullName 属性的 Person 对象数组。但是当我评估JSON.stringify(Array.from(people)) 时,我得到一个没有getter 属性的字符串。

我已经尝试过使用[...people] 而不是Array.from(people)。但同样的结果。 所以是 stringify 动作导致了这个问题(我假设......)。

我怎样才能创建一个返回带有 fullName 属性的数组的响应(基于 fullName getter)?

controller.js

const Person = require('./Person');

exports.getAll = function(req, res, next) {
    Person.findAllPeople()
        .then((people) => {
            res.json(Array.from(people));
        })
        .catch((err) => {return next(err);});
}

Person.js

class Person {
    constructor(personId, first, last, email, birthday) {
        this._id = personId ? personId : undefined;
        this.firstName = first ? first : undefined;
        this.lastName = last ? last : undefined;
        this.email = email ? email : undefined;
        this.birthday = birthday ? new Date(birthday) : undefined;
        this.relations = new Map();
    }
    get fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
    static findAllPeople() {
        return personRepository.getAll("ONLY_NAMES")
            .then((people) => {
                people.forEach((person) => {
                    if (person.relations.size === 0) {
                        person.relations = undefined;
                    }
                })
                return people;
            })
            .catch(console.error);
    }
}
module.exports = Person;

【问题讨论】:

    标签: node.js class express


    【解决方案1】:

    JSON stringify ES6 class property with getter/setter找到解决方案

    我只需要在我的类中添加一个 toJSON 方法...

    toJSON() {
            return {
                _id: this._id,
                firstName: this.firstName,
                lastName: this.lastName,
                fullName: this.fullName,
                birthday: this.birthday,
                email: this.email,
                relations: this.relations
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 2017-11-01
      • 2021-11-16
      相关资源
      最近更新 更多