Node.js NodeJS:返回res.json中类实例的getter属性
在我下面的代码中Node.js NodeJS:返回res.json中类实例的getter属性,node.js,class,express,Node.js,Class,Express,在我下面的代码中 我在Person类中调用静态“findAllPeople”方法。此方法返回一组Person对象 Person类还有一个全名的getter 问题: res.json(Array.from(people))返回Person对象的数组,但不包含fullName属性。 当我在VS代码中调试Array.from(people)时,它会正确返回带有fullName属性的Person对象数组。但是当我计算JSON.stringify(Array.from(people))时,我得到一个没
- 我在Person类中调用静态“findAllPeople”方法。此方法返回一组Person对象
- Person类还有一个全名的getter
res.json(Array.from(people))
返回Person对象的数组,但不包含fullName属性。
当我在VS代码中调试Array.from(people)
时,它会正确返回带有fullName属性的Person对象数组。但是当我计算JSON.stringify(Array.from(people))
时,我得到一个没有getter属性的字符串
我已经尝试使用[…人]
而不是数组。来自(人)
。但同样的结果。
所以是stringify操作导致了这个问题(我假设…)
如何创建一个返回具有fullName属性(基于fullName getter)的数组的响应?
controller.js
Person.js
找到了解决方案
我只需要在我的类中添加一个toJSON方法
toJSON() {
return {
_id: this._id,
firstName: this.firstName,
lastName: this.lastName,
fullName: this.fullName,
birthday: this.birthday,
email: this.email,
relations: this.relations
}
}
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;
toJSON() {
return {
_id: this._id,
firstName: this.firstName,
lastName: this.lastName,
fullName: this.fullName,
birthday: this.birthday,
email: this.email,
relations: this.relations
}
}