node.js sequelize.js - 按 id 查找并返回结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34268597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sequelize.js - Find by id and return result
提问by Vova Mukovozov
I have a function,
我有一个功能,
var findUserDevice = function(userDeviceId){
var device = db.DeviceUser.find({
where: {
id: userDeviceId
}
}).then(function(device) {
if (!device) {
return 'not find';
}
return device.dataValues;
});
};
but this function does not return anything...
但是这个函数不返回任何东西......
var UserDevice = findUserDevice(req.body.deviceUserId);
console.log(UserDevice);// undefined
回答by drinchev
The operation you are trying to do is async, which means that you need to use a callback. Since sequelizeis build on top of Promises, you should actually write your code like this :
您尝试执行的操作是async,这意味着您需要使用回调。因为它sequelize是建立在 Promises 之上的,你实际上应该像这样编写代码:
var findUserDevice = function(userDeviceId){
// return the promise itself
return db.DeviceUser.find({
where: {
id: userDeviceId
}
}).then(function(device) {
if (!device) {
return 'not find';
}
return device.dataValues;
});
};
And later use it like :
然后像这样使用它:
findUserDevice(req.body.deviceUserId).then( function(UserDevice) {
console.log(UserDevice);
});
回答by yoogeeks
If you are getting undefined instead of 'not find' on the console, it means your function is returning a value. The problem might be dataValues is actually undefined. You need to check for the content of device.
如果您在控制台上得到 undefined 而不是“not find”,则意味着您的函数正在返回一个值。问题可能是 dataValues 实际上是未定义的。您需要检查device.
Hint: Try returning just deviceor device.id
提示:尝试只返回device或device.id
PS. If you want to do the search based on id, should go for findById()function of your model.
附注。如果你想根据 id 进行搜索,应该去寻找findById()你模型的功能。
var device = db.DeviceUser.findById(userDeviceId).then(function(device) {
if (!device) {
return 'not find';
}
return device.dataValues;
});
回答by Tyler Long
It's 2019, async& awaitbecome more and more popular. You can change your code to
这是2019年,async与await越来越受欢迎。您可以将代码更改为
const findUserDevice = async function (userDeviceId) {
const device = await db.DeviceUser.find({
where: {
id: userDeviceId
}
})
if (!device) {
return 'not find'
}
return device.dataValues
}
;(async () => {
// ...
const UserDevice = await findUserDevice(req.body.deviceUserId)
console.log(UserDevice)
// ...
})()
IMHO, code above is way more readable.
恕我直言,上面的代码更具可读性。
回答by Diego Santa Cruz Mendezú
This function received params id, this worker for me:
这个函数收到了 params id,这个工人对我来说:
const { customer } = require('../models');
const get = async function(req, res){
let id = req.params.id;
[err, singleCustomer] = await to(customer.findByPk(id, { raw : true }));
return ReS(res, { message :'Obtener cliente: : ', data : JSON.stringify(singleCustomer) });
}

