gpt4 book ai didi

javascript - Node JavaScript express JavaScript 格式数据从 sequelize 查询中获取

转载 作者:行者123 更新时间:2023-12-03 22:38:23 26 4
gpt4 key购买 nike

我在 express JavaScript 框架中使用 sequelize。

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

如果我这样做,我可以像这样很好地检索前端 vue JavaScript spa 中的数据
{
tour_name:"Bali",
activities:[
{name:"Swimming"},
{name:"Beach vollyball"},
]
}

上面一个是为前端检索数据。

如果我需要获取数据并在发送之前在 Controller 中进行一些更改,我将 raw: true
然后我可以在我的 Controller 中获得相同的输出。但问题是 raw:真正的
连接,因此从 Controller 获取数据并对其进行一些更改非常困难。
我必须访问这么多嵌套对象才能找到我想要的数据。有没有更聪明的方法(应该有)来获得上述格式
从 Controller 不使用 raw: true

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

最佳答案

在下面的代码中,我必须检索商店产品图像及其 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 查询有点复杂,但创建一个通用函数来格式化为所需的输出将非常有用。

关于javascript - Node JavaScript express JavaScript 格式数据从 sequelize 查询中获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com