kroe761
kroe761

Reputation: 3534

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.

Upvotes: 5

Views: 4504

Answers (2)

bahri noredine
bahri noredine

Reputation: 751

my friend is very simple to do logic on your result in same place that your retrieve you data for example in your code that i modify :

router.get('/', (req, res, next) => {
     var users = models.User.findAll({
            attributes: ['id', 'name'],
            raw: true
        }).then((results) => {            
            //here do you logic with results 
              //after
                res.status(200).json({data : result});
        }).catch(error => res.status(400).json({error}));
});

Upvotes: 0

Daksh M.
Daksh M.

Reputation: 4817

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.

Upvotes: 2

Related Questions