Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data from Sequelize query as a plain JavaScript object in a variable?

I am writing a node API and want to save the results of a Sequelize query in a variable as a plain JavaScript object outside of the findAll block. I have something that works, but not as well as I would like. Here is what I have:

router.get('/', (req, res, next) => {

    models.User.findAll({
        attributes: ['id', 'name'],
        raw: true
    }).then(function (results) {

        console.log(results); // Plain JavaScript object, which is good

        // Do logic on results 

        //Return results
        res.status(200).json({
            results
        });
    });
});

But I really don't want to keep all my logic within the then() block, especially since I might want to do some other queries before or after this one. I really want something like (if this was a thing):

router.get('/', (req, res, next) => {

    var users = models.User.findAll({
        attributes: ['id', 'name'],
        raw: true
    }).then(function (results) {            
        });
    });

    // Do logic on results

    // return results
    res.status(200).json({
        results
    });
});

I tried to save the sequelize query in a function below the router.get() call and return the results while they were a JavaScript object, but that didn't work. I am very new to JavaScript, so I appreciate the advice.

like image 958
kroe761 Avatar asked Oct 28 '22 07:10

kroe761


1 Answers

Well, if you don't want your logic code in the then block, you might as well use async-await:

router.get('/', async (req, res, next) => {

    var results = await models.User.findAll({
        attributes: ['id', 'name'],
        raw: true
    });

     // you've result variable available here, use it.
    // Do logic on results

    // return results
    res.status(200).json({
        results
    });
});

now you don't have to write the code in then block, you can just use the variable results in the function directly.

like image 98
Daksh Miglani Avatar answered Nov 09 '22 15:11

Daksh Miglani