gpt4 book ai didi

node.js - 如何使用带有 where 子句的 json 对象?

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

我想要实现的目标

查找经过身份验证的用户团队中的所有玩家。

问题是什么?

无法在 const findUsers = await User.findAll where 子句中使用返回的 json,我不确定这是否是正确的方法。

数据库表

用户表:id (PK) 等

团队:id (PK) 等

TeamUsers: id , TeamID (Foreign Key) , UserID (Foreign Key) 等

从 FindTeamUsers (Var ob) 返回 Json,这是正确的

[{"id":2,"TeamID":1,"UserID":1,"createdAt":"2019-08-09","updatedAt":"2019-08-09"},{"id":3,"TeamID":1,"UserID":3,"createdAt":"2019-08-09","updatedAt":"2019-08-09"},{"id":76,"TeamID":1,"UserID":5,"createdAt":"2019-08-22","updatedAt":"2019-08-22"}]

以下是我目前使用 Nodejs、ExpressJS 使用的路由
router.get('/Team', auth, async function(req, res) {

// -- Get the Users team that is currently Authenticated (req.user.id (auth) )
const findTeam = await TeamUsers.findOne({
where: {
UserID: req.user.id
}
});

//If the User has a team
if (findTeam) {

// -- Get the players Team Mates who have the matching TeamID
const findTeamUsers = await TeamUsers.findAll({

where: {
TeamID: findTeam.TeamID
}

});
//Store the object and Display in JSON FORMAT
var ob = JSON.stringify(findTeamUsers);
console.log(ob);

if (!findTeamUsers) {
console.log('error');
} else {
//find the Users Details From the Users Table Model
//findTeamUsers - Is an array of each record found from const findTeamUsers = await TeamUsers.findAll
const findUsers = await User.findAll({
where: {
id: ob.UserID
}
});

res.status(200).json(findUsers);


}
}

});

最佳答案

你的 ob 是一个 string 所以 ob.UserIDundefinedfindTeamUsers ( FindTeamUsers 结果) 是一个对象数组,因此 findTeamUsers.UserID 也将是 undefined。 (数组 findTeamUsers 没有属性 UserID )。

您可以传递 an array of UserIDs to search multiple elements (如果您想查找数组中的所有 UserID ):

User.findAll({
where: {
id: findTeamUsers.map(o => o.UserID)
}
})

关于node.js - 如何使用带有 where 子句的 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57731851/

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