我试图添加新的键值到mysql结果对象,但它现在工作如何修复它?
我正在尝试从post数据库获取所有post,并检查post_likes表中的post是否为like,如果为like,则在post请求对象中添加{isLike:true},否则为false
const fetchPost = (req, res, next) => {
const sql = "SELECT account.name,account.username,post.content,post.likes, post.visibility,post.date,post.time, post.profile, post.id FROM post INNER JOIN account ON account.uid = post.user_id WHERE post.visibility = 'Friends' OR post.visibility = 'Public'";
// const sql = "SELECT * FROM post";
connectDB.query(sql, (err, post_result) => {
if (err) {
console.log(err);
return next(createCustomError(err, 400));
}
const get_uid_query = `SELECT id FROM account where uid = '${req.user['uid']}'`;
// get the id of user by uid
connectDB.query(get_uid_query, (err, user_id_result) => {
if (err) throw err;
const id = (user_id_result[0]['id']);
for (let i = 0; i < post_result.length; i++) {
const sql = `SELECT user_id, post_id FROM post_likes WHERE post_id = ${post_result[i]['id']} AND user_id = ${id}`;
connectDB.query(sql, (err, result) => {
if (err) throw err;
else if (result.length > 0) {
post_result[i]['isliked'] = true;
} else {
post_result[i]['isLiked'] = false;
}
})
}
res.status(200).json(post_result); // isLiked value not sending with the response how to fix it
})
})
}
1条答案
按热度按时间hgc7kmma1#
当您只需要一个查询就可以轻松获取信息时,您就不必要运行多个查询了。
我不是很熟悉node.js,所以这可能有错误: