Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize.js - Find by id and return result

Tags:

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 
like image 358
Vova Mukovozov Avatar asked Dec 14 '15 13:12

Vova Mukovozov


People also ask

How do I get data by ID in Sequelize?

If you want to do the search based on id, should go for findById() function of your model. Save this answer.

What does Sequelize return?

Sequelize uses an option called returning to specify which data returns from a commands like . destroy() or update() . Let's look at three common Sequelize commands and see how to handle the data returned by each.

What does findByPk return?

findByPk. Returns the row with the given value of Primary Key.


1 Answers

The operation you are trying to do is async, which means that you need to use a callback. Since sequelize is build on top of Promises, you should actually write your code like this :

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); });  
like image 106
drinchev Avatar answered Oct 09 '22 16:10

drinchev