javascript - nodejs“this”在转换中未定义
问题描述
这是我的转换代码
我不知道为什么这在转换后未定义以使用 showCategories
const Transform = require('../.././transform');
module.exports = class postTransform extends Transform {
transform(item) {
return {
'id' : item._id ,
'title' : item.title,
...this.showCategories(item) //here is the error
}
}
showCategories(item) {
const categoryTransform = require('./categoryTransform');
if(this.withCategoriesStatus) {
return {
categories : new categoryTransform().transformCollection(item.categories)
}
}
return {}
}
withCategories() {
this.withCategoriesStatus = true;
return this;
}
}
这是我的路线
////some code
const HomePostController = require(`${ControllerApi}/v1/postController`);
homePostRouter.get('/posts' , HomePostController.index.bind(HomePostController));
////some code
和我的后控制器代码
module.exports = new class postController extends Controller {
index(req , res) {
const page = req.query.page || 1
this.model.Post.paginate({} , { page , limit : 21 , populate : ['categories']})
.then(result => {
if(result) {
return res.json({
data : new postTransform().withPaginate().transformCollection(result),
success : true ,
status : 200
});
}
res.json({
message : 'Posts empty',
success : false ,
status : 404
})
})
.catch(err => console.log(err));
}
我想在调用我在帖子模型中使用的所有帖子时显示相关类别和标签到类别和标签模型
解决方案
你新建了你的类,并且没有构造函数。您没有调用转换函数,我也没有看到withPaginate()
定义。是在单独的文件中吗?
我认为通读本文将有助于在 JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes中使用类。如果您在阅读完本文后仍然需要帮助,我将尝试引入您的示例并与您一起完成它。
推荐阅读
- docker - 在 Windows 中托管的 ubuntu 容器中列出包含 200K 文件的共享卷中的目录内容会卡住
- serialization - 为什么在反序列化 Elixir 映射时 `erl_decode` 返回 NULL?
- reactjs - 是否可以映射多个项目?
- wordpress - WP REST API 上自定义帖子/关系的 ACF、类别和特色图片
- swift - CGImage 平均性能缓慢
- ruby-on-rails - Rails 控制器集成测试 - 预期响应为 <2XX:成功>,但为 <500:内部服务器错误>
- python - 如何使用 Pyrebase 使用 Firebase 实时数据库流?
- mysql - 1 表示单列中的 r 关系
- intellij-idea - 如何让 IntelliJ 在每个新项目中默认插入版权标头?
- python - 从 App Annie API 提取数据比较智能 - python