Sequelize, convert entity to plain object

后端 未结 9 1114
说谎
说谎 2020-12-12 16:53

I\'m not very familiar with javascript, and stunning, because i can\'t add new property, to object, that fetched from database using ORM names Sequelize.js.

To avoid

相关标签:
9条回答
  • 2020-12-12 17:32

    For nested JSON plain text

    db.model.findAll({
      raw : true ,
      nest : true
    })
    
    0 讨论(0)
  • 2020-12-12 17:39

    As CharlesA notes in his answer, .values() is technically deprecated, though this fact isn't explicitly noted in the docs. If you don't want to use { raw: true } in the query, the preferred approach is to call .get() on the results.

    .get(), however, is a method of an instance, not of an array. As noted in the linked issue above, Sequelize returns native arrays of instance objects (and the maintainers don't plan on changing that), so you have to iterate through the array yourself:

    db.Sensors.findAll({
        where: {
            nodeid: node.nodeid
        }
    }).success((sensors) => {
        const nodeData = sensors.map((node) => node.get({ plain: true }));
    });
    
    0 讨论(0)
  • you can use the query options {raw: true} to return the raw result. Your query should like follows:

    db.Sensors.findAll({
      where: {
        nodeid: node.nodeid
      },
      raw: true,
    })
    

    also if you have associations with include that gets flattened. So, we can use another parameter nest:true

    db.Sensors.findAll({
      where: {
        nodeid: node.nodeid
      },
      raw: true,
      nest: true,
    })
    
    0 讨论(0)
提交回复
热议问题