首页 > 解决方案 > 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));
    }

我想在调用我在帖子模型中使用的所有帖子时显示相关类别和标签到类别和标签模型

标签: javascriptnode.js

解决方案


你新建了你的类,并且没有构造函数。您没有调用转换函数,我也没有看到withPaginate()定义。是在单独的文件中吗?

我认为通读本文将有助于在 JavaScript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes中使用类。如果您在阅读完本文后仍然需要帮助,我将尝试引入您的示例并与您一起完成它。


推荐阅读