Node Js - Function to Return Array of Objects Read from Sequelize Database

Node js - function to return array of objects read from sequelize database

Here are the changes you need to do to get expected result :

function getInvoicesCount() {
...
return db.userInvoices.findAll({ //<-------- 1. First add return here
...
}).then(result => {
...
return promiseInvoices; //<----------- 2. Put this line inside the then
});
// return promiseInvoices; //<----------- Remove this line from here
}

getInvoicesCount().then(data => {
console.log(data); // <------- Check the output here
})

Explanation for this :

To get .then when you can function , function should return promise ,
but in you case you are just returning a blank array ,

As per the sequlize doc , db.userInvoices.findAll returns the
promise so all you need to do is add return before the this function
, First step is done

You were return promiseInvoices; at wrong place , why ? , coz at
that you will never get the result , as the code above it run in async
manner as it is promise , so you will always get the balnk array , to
get the expected result you should return it from
db.userInvoices.findAll's then function as shown above in code

Node js - function to return array of data read from database

Something like this should do the trick:

function loadTokens(userIds) {
var promises = userIds.map(item => admin.database().ref('/users/' + item).once('value'));
return Promise.all(promises).then(snapshots => {
return snapshots.map(snapshot => snapshot.val().fcmToken);
});
}

So we're using Promise.all() to wait for all tokens to be loaded, and return the token from our then completion handler.

Matching arrays returned from sequelize with Jest

I think it's not a good idea to compare the whole Models (lot's of stuff you don't care about in there). Try to compare the dataValues instead. Make sure you don't use raw: true in your findAll call because then you don't have the dataValues property.

const allAddresses = await controller._getAll();
const addressesPlain = allAddresses.map(address => address.dataValues);

expect([address_1.dataValues, address_2.dataValues]).toEqual(addressesPlain);

If you're interested in the small test case I wrote: https://pastr.io/view/QKNmua

Sequelize return array with Strings instead of Objects

Using Sequelize 3.13.0 it looks like it isn't possible to have find return a flat array of values rather than an array of objects.

One solution to your problem is to map the results using underscore or lodash:

AccountModel.findAll({
where: {
Age: {
$gt : 18
}
},
attributes: ['Name'],
raw : true
})
.then(function(accounts) {
return _.map(accounts, function(account) { return account.Name; })
})

I've uploaded a script that demonstrates this here.

As a quick note, setting raw: true makes the Sequelize find methods return plain old JavaScript objects (i.e. no Instance methods or metadata). This may be important for performance, but does not change the returned values after conversion to JSON. That is because Instance::toJSON always returns a plain JavaScript object (no Instance methods or metadata).

How to get data from database in array format using node js and MySql

Nodejs will send you a JSON response if you want to change it. It is better to change or maniuplate it in a Front end framework. But if you want to change it in backend as you have asked Make sure that the rows is in the format that you want to recive.

 let data = [ 
{ "name": "Dheeraj", "amount": "77.0000" },
{ "name": "Raju", "amount": "255.0000" }
]
// empty array to store the data
let testData = [];
data.forEach(element => {
testData.push(element.name)
});

Sequelize include array of nested object - node.js

Solution:

findById: function(id) {
return db.channel.findOne({
logging: true,
include: [
{ model: db.track, attributes: ['id', 'name','artist_name' ,'album_name'], as: 'track'},
{ model: db.track, attributes: ['id', 'name','artist_name' ,'album_name'], as: 'tracks', paranoid: true, required: false}
],
where: {
id: id
}
});
},

Sequelize does not return object but instead extra data

You just got a sequelize model object instance with its own additional props and methods.
To get plain object do this:

const plainUser = user.get({ plain: true })
console.log(plainUser)


Related Topics



Leave a reply



Submit