Sequelize - How to Return Json Objects of the Database Results Only

Sequelize - How can I return JSON objects of the database results only?

Though poorly documented, this does exist in Sequelize.

Couple Ways:

1. For any response object that resulted from a query, you can extract only the data you want by appending .get({plain:true}) the the response like so:

Item.findOrCreate({...})
.spread(function(item, created) {
console.log(item.get({
plain: true
})) // logs only the item data, if it was found or created

Also make sure you are using the spread callback function for your type of dynamic query promise. And note that you have access to a boolean response, created, which signifies whether or not a create query was executed.

2. Sequelize provides the raw option. Simply add the option {raw:true} and you will receive only the raw results. This will work on an array of results, the first method should not, as get will not be a function of an array.

Sequelize find in JSON field

According to this link
You can approach the answer via 3 ways:

Nested Key

{
"meta.audio.length": {
[Op.gt]: 20
}
}

Nested object

{
meta: {
video: {
url: {
[Op.ne]: null
}
}
}
}

Containment

{
"meta": {
[Op.contains]: {
site: {
url: 'http://google.com'
}
}
}
}

Return data only without field name in Sequelize ORM

No, {"data"} isn't a valid JSON structure. You could convert it to an array of "datas" using Array.map(); passing raw: true to findAll() will return an array of plain JSON objects which is more efficient than converting to Model Instances first before mapping them to just the values you want.

const results = await Model.findAll({
attributes: ['value'],
where: {
code: { [Op.like]: 'images_default_droplet_%' },
is_published: 1
},
raw: true, // return array of plain JSON objects
});

// 'datas' is an array of ["data","data","data"...]
const datas = results.map((result) => result.value);

How to pass the output of a Sequelize query to another function that will return a JSON object with express?

I can't answer your last question about the format of your data because I'm unfamiliar with Sequelize, but the trouble you're having passing the data to your ExpressJS response stems from a lack of understanding of the Promise pattern. Have your service function return the Promise instead:

// services/orders.js
import { Order } from '../models'
const test = () => Order.findAll();
// export test at some point

And then call the service function inside your controller to access the returned data:

// controllers/orders.js
function getOrders(req, res) {
orderServices.test()
.then(data => res.send({ data }));
}

Look into asynchronous programming patterns- callbacks first, then Promises- and the reasoning behind why you must take this approach will become clear.

This answer should cover a considerable amount of the relevant subject matter.



Related Topics



Leave a reply



Submit