重命名带有Sequalize的EmiratesToMany关联

时间:2019-11-22 16:02:11

标签: javascript node.js sequelize.js

给出该关联

Product.Locations = Product.belongsToMany(ProductLocation, { 
   as: 'locations', 
   through: ProductStock,
   foreignKey: 'productId',
   otherKey: 'locationId'
});

已加载以下模型

const product = await Product.findById(123, { include: Product.Locations });
console.log(product);
// -> {
//   id: 123,
//   ....,
//   locations: [ {
//      ProductStock: { productId: 123, locationId: 456, stock: 99 },
//      id: 456,
//      ...
//   } ],
//   ...
// }

如何将名称ProductStock更改为stock

1 个答案:

答案 0 :(得分:0)

只需尝试以下代码:

    var str=
    {
      id: 123,
      locations: 
      [ 
        {
            ProductStock: { productId: 123, locationId: 456, stock: 99 },
            id: 456,
        },
      ],
    };
    var str2=
    {
      id:str.id,
      locations:
      [
        {
          stock:
          { 
            productId:str.locations[0].ProductStock.productId,
            locationId:str.locations[0].ProductStock.locationId,
            stock:str.locations[0].ProductStock.stock
          },
          id:str.locations[0].id
        }
      ]
    };
    console.log(JSON.stringify(str2));