ORM: Sequelize: How can I return json except for some data?

Asked 1 years ago, Updated 1 years ago, 58 views

Hello.

This is a question about the sort query. Queries three tables of many-to-many relationships. If you query as below:

const data = await product.findOne({
   where: { product_id: id },
   include: [
     {
       model: category
     }
   ]
 });

Return json data as below:

"category": {
     "product_id": 1,
     "name": "Arc d'Triomphe",
     "description": "This beautiful and iconic T-shirt will no doubt lead you to your own triumph.",
     "price": "14.99",
     "discounted_price": "0.00",
     "image": "arc-d-triomphe.gif",
     "image_2": "arc-d-triomphe-2.gif",
     "thumbnail": "arc-d-triomphe-thumbnail.gif",
     "display": 0,
     "categories": [
         {
             "category_id": 1,
             "name": "French",
             "description": "The French have always had an eye for beauty. One look at the T-shirts below and you'll see that same appreciation has been applied abundantly to their postage stamps. Below are some of our most beautiful and colorful T-shirts, so browse away! And don't forget to go all the way to the bottom - you don't want to miss any of them!",
             "department_id": 1,
             "product_category": {
                 "product_id": 1,
                 "category_id": 1
             }
         }
     ]
}

I would like to make the above json data as below. How do I query this?

"category": [
        {
            "category_id": 1,
            "name": "French",
            "department_id": 1
        }
    ]

If you need a model file, could you leave a comment?

Thank you.

sequelize.js json

2022-09-22 18:07

1 Answers

Query as below.

const query = await product.findOne({
   where: { product_id: id },
   include: {
     model: category,
     attributes: ['category_id', 'name', 'department_id'],
     through: { attributes: [] }
   },
   attributes: []
});

Then you get the json data as below. Here, you can peel off the array bracket separately.

 "category": {
     "categories": [
         {
             "category_id": 1,
             "name": "French",
             "department_id": 1
         }
     ]
 }

The keypoint was through: { attributes: []} .


2022-09-22 18:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.