有效的 Postgres 查询总是 return 未定义
Valid Postgres query alway return undefined
我正在使用 sails 构建一个 API,我的一个函数需要从我的 PGSQL 数据库中获取列。当我在 PGadmin 中测试时,我的 SQL 请求正在运行,它看起来像这样:
SELECT "user".id, "user".picture, "user".first_name, "trophe".trophe FROM "user" INNER JOIN "trophe" ON "trophe".user = "user".id WHERE "trophe".foot = 1
当我在 sails API 中转录这个请求时,它看起来像这样:
getHommeAndChevre: function (req, res) {
console.log(req.param("id"));
Trophe.query("SELECT 'user'.id, 'user'.picture, 'user'.first_name, 'trophe'.trophe FROM 'user' INNER JOIN 'trophe' ON 'trophe'.user = 'user'.id WHERE 'trophe'.foot ="+req.param('id'), function(err,trophes){
if(!trophes) {return res.status(400).end();}
if(trophes){
_each(trophes, function(trophe){
if (trophe.trophe == 0) {var chevre = trophe};
if (trophe.trophe == 1) { var homme = trophe};
})
return res.status(200).json({chevre: chevre, homme: homme})
}
});
}
但是无论我做什么 Trophe.query 总是返回 undefined
。这里可能有什么问题?
对标识符使用双引号
Trophe.query('SELECT "user".id, "user".picture, "user".first_name, ...
您的 return 在回调之外,因此您 return 查询结束前的值。
_each(trophes, function(trophe, index){
if (trophe.trophe == 0) {var chevre = trophe};
if (trophe.trophe == 1) { var homme = trophe};
if (index == trophes.length - 1) //End of the loop
return res.status(200).json({chevre: chevre, homme: homme});
})
我正在使用 sails 构建一个 API,我的一个函数需要从我的 PGSQL 数据库中获取列。当我在 PGadmin 中测试时,我的 SQL 请求正在运行,它看起来像这样:
SELECT "user".id, "user".picture, "user".first_name, "trophe".trophe FROM "user" INNER JOIN "trophe" ON "trophe".user = "user".id WHERE "trophe".foot = 1
当我在 sails API 中转录这个请求时,它看起来像这样:
getHommeAndChevre: function (req, res) {
console.log(req.param("id"));
Trophe.query("SELECT 'user'.id, 'user'.picture, 'user'.first_name, 'trophe'.trophe FROM 'user' INNER JOIN 'trophe' ON 'trophe'.user = 'user'.id WHERE 'trophe'.foot ="+req.param('id'), function(err,trophes){
if(!trophes) {return res.status(400).end();}
if(trophes){
_each(trophes, function(trophe){
if (trophe.trophe == 0) {var chevre = trophe};
if (trophe.trophe == 1) { var homme = trophe};
})
return res.status(200).json({chevre: chevre, homme: homme})
}
});
}
但是无论我做什么 Trophe.query 总是返回 undefined
。这里可能有什么问题?
对标识符使用双引号
Trophe.query('SELECT "user".id, "user".picture, "user".first_name, ...
您的 return 在回调之外,因此您 return 查询结束前的值。
_each(trophes, function(trophe, index){
if (trophe.trophe == 0) {var chevre = trophe};
if (trophe.trophe == 1) { var homme = trophe};
if (index == trophes.length - 1) //End of the loop
return res.status(200).json({chevre: chevre, homme: homme});
})