从sequlize查询中获取Node js express js格式数据

时间:2019-02-28 07:31:45

标签: javascript node.js express sequelize.js

嗨,我在express js框架中使用sequlize。

const data = await db.Tour.findAll();
res.status(200).json(data)

如果执行此操作,我可以像这样在前端vue js spa中很好地检索数据

{
    tour_name:"Bali",
    activities:[
        {name:"Swimming"},
        {name:"Beach vollyball"},
    ]
}

以上是检索前端数据的方法。

如果我需要获取数据并在发送它们之前在控制器中进行一些更改,我将raw:true 然后我可以在控制器中获得相同的输出。但是问题是 raw:true 与 连接,因此很难从控制器获取数据并对其进行一些更改。 我必须访问许多嵌套对象才能找到所需的数据。是否有更聪明的方法(应该有)来获取上述格式 无需使用 raw:true

我希望必须有一种很好的方法将该数据对象传递给某些东西并转换为格式。 我该如何实现?

任何帮助! 谢谢你。

1 个答案:

答案 0 :(得分:0)

在下面的代码中,我不得不检索商店产品图像及其ID以及其他一些数据,例如评分,计数等。

In below code I had to retrieve a shop products images and its ids.


exports.filterShopListings = async (data) => {

    return Db.sequelize.query("SELECT productImages, S.shopId, S.currency, S.mainImage, S.mainImageThumb, S.coverImage, S.coverImageThumb, S.name, S.location, S.approved, S.locationLatitude, CONCAT('"+process.env.QR_URL+"',S.qrCode) as qrCode, S.locationLongitude, COALESCE(productCount,0) as productCount, COALESCE(ratingCount,0) as ratingCount, COALESCE(ROUND(UR.ratingAvg,1) ,0) as ratings, COALESCE(shopFollowing,0) as followingCount FROM shops as S JOIN users U ON (U.userId=S.userId AND U.blocked='0') LEFT JOIN ( SELECT COUNT(*) as productCount, shopId, GROUP_CONCAT(mainImageThumb,'--',shopProductId) as productImages FROM shopProducts WHERE shopProducts.deleted='0' AND shopProducts.blocked='0' GROUP BY shopId)  SP ON (SP.shopId=S.shopId) LEFT JOIN ( SELECT COUNT(*) as ratingCount, AVG(ratings) as ratingAvg, shopId FROM userRatings WHERE userRatings.blocked='0' AND userRatings.deleted='0' GROUP BY shopId ) UR ON (UR.shopId=S.shopId) LEFT JOIN ( SELECT COUNT(*) as shopFollowing, shopId FROM shopFollowings GROUP BY shopId) SF ON (SF.shopId=S.shopId) WHERE "+data.whereString+" HAVING "+data.havingString+" ORDER BY "+data.orderingParam+" "+data.orderingSort+" LIMIT "+data.skip+", "+data.take+" ",{ type: Sequelize.QueryTypes.SELECT})
        .then( (shops) => {

            shops = JSON.parse(JSON.stringify(shops));

            shops.forEach(  (shop) => {

                //shop.productImagesTemp  = shop.productImages;
                shop.productImages = shopImagesFunc(shop.productImages);

            });

            return shops;

        });

};

还有shopImagesFunc代码-

    var shopImagesFunc = (productImages) => {

    if(productImages ==null)
        return [];

    var images = (productImages.split(",").filter(Boolean));

    var newImages = [];
    images.forEach(image => {

        let temp = image.split("--").filter(Boolean);

        newImages.push({
            shopProductId: parseInt(temp[1]),
            mainImage: temp[0],
        });

    });

    return newImages;

};

SQL查询并不复杂,但是创建一个通用函数来格式化为所需的输出将非常有用。