I'm trying to get all rows with specific ID in async/await
style using sequelize
. My code looks like:
UPDATED:
router.get('/', errorHandler(async (req, res, next) => {
let domainsDB = await Domain.findAll({
where: { accID: accID },
attributes: [`adID`, `domain`, `status`]
})
}
When I console.log(domainsDB)
I see this:
[
domains {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
__eagerlyLoadedAssociations: [],
isNewRecord: false },
domains {
...
...
...
]
The docs says it has to be an array in return. But console log shows this is an object. The data in this object in dataValues
is correct. There are my domains. But I expect to get an array to work with.
How to get an array in return with async/await?
Thank you for any help.
I'm trying to get all rows with specific ID in async/await
style using sequelize
. My code looks like:
UPDATED:
router.get('/', errorHandler(async (req, res, next) => {
let domainsDB = await Domain.findAll({
where: { accID: accID },
attributes: [`adID`, `domain`, `status`]
})
}
When I console.log(domainsDB)
I see this:
[
domains {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
__eagerlyLoadedAssociations: [],
isNewRecord: false },
domains {
...
...
...
]
The docs says it has to be an array in return. But console log shows this is an object. The data in this object in dataValues
is correct. There are my domains. But I expect to get an array to work with.
How to get an array in return with async/await?
Thank you for any help.
2 Answers
Reset to default 18All you need is : raw : true
,
let domainsDB = await Domain.findAll({
where: { accID: accID },
attributes: [`adID`, `domain`, `status`],
raw : true // <--- HERE
})
By default model queries returns the sequelize
Object , to get the plain result we need to pass raw : true
await should be wrapped in a function with async key in it.
A correct code snippet would look like this:
async fetchData(accID) {
return await Domain.findAll({
where: { accID: accID },
attributes: [`adID`, `domain`, `status`]
})
}
let data = fetchData(1);
console.log(data);
Alternative approaches are: 1) using generator functions 2) promises.
They're basically the same thing in a manner that it makes your synchronous code act as asynchronous.
let domainsDB
? – Mehrdad Shokri Commented Dec 4, 2018 at 11:46[
and ends with]
– Khauri Commented Dec 4, 2018 at 12:05