Sequelize,将实体转换为普通对象

Rus*_*lan 72 node.js sequelize.js

我对javascript并不是很熟悉,并且令人惊叹,因为我无法使用ORM名称Sequelize.js从数据库中添加新属性到对象.

为了避免这种情况,我使用这个hack:

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    }
}).success(function (sensors) {
        var nodedata = JSON.parse(JSON.stringify(node)); // this is my trick
        nodedata.sensors = sensors;
        nodesensors.push(nodedata);
        response.json(nodesensors);
});
Run Code Online (Sandbox Code Playgroud)

那么,通常的方法是向对象添加新属性.

如果它可以帮助,我使用sequelize-postgres版本2.0.x.

UPD.的console.log(节点):

{ dataValues: 
   { nodeid: 'NodeId',
     name: 'NameHere',
     altname: 'Test9',
     longname: '',
     latitude: 30,
     longitude: -10,
     networkid: 'NetworkId',
     farmid: '5',
     lastheard: Mon Dec 09 2013 04:04:40 GMT+0300 (FET),
     id: 9,
     createdAt: Tue Dec 03 2013 01:29:09 GMT+0300 (FET),
     updatedAt: Sun Feb 23 2014 01:07:14 GMT+0300 (FET) },
  __options: 
   { timestamps: true,
     createdAt: 'createdAt',
     updatedAt: 'updatedAt',
     deletedAt: 'deletedAt',
     touchedAt: 'touchedAt',
     instanceMethods: {},
     classMethods: {},
     validate: {},
     freezeTableName: false,
     underscored: false,
     syncOnAssociation: true,
     paranoid: false,
     whereCollection: { farmid: 5, networkid: 'NetworkId' },
     schema: null,
     schemaDelimiter: '',
     language: 'en',
     defaultScope: null,
     scopes: null,
     hooks: { beforeCreate: [], afterCreate: [] },
     omitNull: false,
     hasPrimaryKeys: false },
  hasPrimaryKeys: false,
  selectedValues: 
   { nodeid: 'NodeId',
     name: 'NameHere',
     longname: '',
     latitude: 30,
     longitude: -110,
     networkid: 'NetworkId',
     farmid: '5',
     lastheard: Mon Dec 09 2013 04:04:40 GMT+0300 (FET),
     id: 9,
     createdAt: Tue Dec 03 2013 01:29:09 GMT+0300 (FET),
     updatedAt: Sun Feb 23 2014 01:07:14 GMT+0300 (FET),
     altname: 'Test9' },
  __eagerlyLoadedAssociations: [],
  isDirty: false,
  isNewRecord: false,
  daoFactoryName: 'Nodes',
  daoFactory: 
   { options: 
      { timestamps: true,
        createdAt: 'createdAt',
        updatedAt: 'updatedAt',
        deletedAt: 'deletedAt',
        touchedAt: 'touchedAt',
        instanceMethods: {},
        classMethods: {},
        validate: {},
        freezeTableName: false,
        underscored: false,
        syncOnAssociation: true,
        paranoid: false,
        whereCollection: [Object],
        schema: null,
        schemaDelimiter: '',
        language: 'en',
        defaultScope: null,
        scopes: null,
        hooks: [Object],
        omitNull: false,
        hasPrimaryKeys: false },
     name: 'Nodes',
     tableName: 'Nodes',
     rawAttributes: 
      { nodeid: [Object],
        name: [Object],
        altname: [Object],
        longname: [Object],
        latitude: [Object],
        longitude: [Object],
        networkid: [Object],
        farmid: [Object],
        lastheard: [Object],
        id: [Object],
        createdAt: [Object],
        updatedAt: [Object] },
     daoFactoryManager: { daos: [Object], sequelize: [Object] },
     associations: {},
     scopeObj: {},
     primaryKeys: {},
     primaryKeyCount: 0,
     hasPrimaryKeys: false,
     autoIncrementField: 'id',
     DAO: { [Function] super_: [Function] } } }
Run Code Online (Sandbox Code Playgroud)

接下来我想你会想到:"好的,这很容易,只需将你的属性添加到dataValues即可."

node.selectedValues.sensors = sensors;
node.dataValues.sensors = sensors;
Run Code Online (Sandbox Code Playgroud)

我添加这些行,这不起作用

lut*_*act 108

您可以使用查询选项{raw: true}返回原始结果.您的查询应如下所示:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  },
  raw: true,
})
Run Code Online (Sandbox Code Playgroud)

  • "raw:true"将以某种方式展平由关联模型注入的数组.到目前为止,我发现的唯一工作是configs = JSON.parse(JSON.stringify(configs)); (21认同)
  • @SoichiHayashi 要获得原始但嵌套的结果,您可以使用 `nest: true` 和 `raw: true` 。 (7认同)

Cha*_*esA 94

对于那些最近遇到这个问题的人.values来说,从Sequelize 3.0.0开始就被弃用了.使用.get(),而不是拿到普通的JavaScript对象.所以上面的代码将改为:

var nodedata = node.get({ plain: true });
Run Code Online (Sandbox Code Playgroud)

Sequelize docs在这里

  • 如果我错了,请纠正我 - 但我不认为这会对一系列行有效吗?例如,使用.findAndcount,你必须.map结果行并返回每个.get来获得你需要的东西. (6认同)
  • 使用`.get()`不会转换包含的关联,而是使用`.get({plain:true})`.感谢您提及文档中的建议. (3认同)

sde*_*old 37

如果我找到你,你想要将sensors收藏添加到node.如果两个模型之间有映射,则可以使用此处说明的include功能或在每个实例上定义的getter.你可以在这里找到相关的文档.values

后者可以像这样使用:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  }
}).success(function (sensors) {
  var nodedata = node.values;

  nodedata.sensors = sensors.map(function(sensor){ return sensor.values });
  // or
  nodedata.sensors = sensors.map(function(sensor){ return sensor.toJSON() });

  nodesensors.push(nodedata);
  response.json(nodesensors);
});
Run Code Online (Sandbox Code Playgroud)

有机会也nodedata.sensors = sensors可以.

  • 谢谢,我需要的一切:node.values :) (2认同)

Viv*_*shi 28

最好和简单的做法是:

只需使用Sequelize的默认方式

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    raw : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});
Run Code Online (Sandbox Code Playgroud)

注意:[options.raw]:返回原始结果.有关更多信息,请参阅sequelize.query.

  • 如果您有一个子数据数组,您将得到错误的结果。因此,如果发布的查询仅返回一个带有子“someModel”数组的“sensors”,您将获得一个“sensors”的“数组”,每个传感器中都有一个“someModel”。 (7认同)
  • “raw”结果还省略了所有“VIRTUAL”属性值。 (2认同)

Sha*_*hes 26

正如CharlesA在他的回答中指出的那样,技术上已.values()被弃用,尽管文档中没有明确指出这一事实.如果您不想{ raw: true }在查询中使用,首选方法是调用.get()结果.

.get()但是,它是实例的方法,而不是数组的方法.如上面链接的问题所述,Sequelize返回实例对象的本机数组(并且维护者不打算更改它),因此您必须自己遍历数组:

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    }
}).success((sensors) => {
    const nodeData = sensors.map((node) => node.get({ plain: true }));
});
Run Code Online (Sandbox Code Playgroud)


eve*_*ost 9

这就是我用来从sequelizev4查询获取具有非字符串化值和所有嵌套关联的普通响应对象的方法。

使用纯JavaScript(ES2015 +):

const toPlain = response => {
  const flattenDataValues = ({ dataValues }) => {
    const flattenedObject = {};

    Object.keys(dataValues).forEach(key => {
      const dataValue = dataValues[key];

      if (
        Array.isArray(dataValue) &&
        dataValue[0] &&
        dataValue[0].dataValues &&
        typeof dataValue[0].dataValues === 'object'
      ) {
        flattenedObject[key] = dataValues[key].map(flattenDataValues);
      } else if (dataValue && dataValue.dataValues && typeof dataValue.dataValues === 'object') {
        flattenedObject[key] = flattenDataValues(dataValues[key]);
      } else {
        flattenedObject[key] = dataValues[key];
      }
    });

    return flattenedObject;
  };

  return Array.isArray(response) ? response.map(flattenDataValues) : flattenDataValues(response);
};
Run Code Online (Sandbox Code Playgroud)

使用lodash(更加简洁):

const toPlain = response => {
  const flattenDataValues = ({ dataValues }) =>
    _.mapValues(dataValues, value => (
      _.isArray(value) && _.isObject(value[0]) && _.isObject(value[0].dataValues)
        ? _.map(value, flattenDataValues)
        : _.isObject(value) && _.isObject(value.dataValues)
          ? flattenDataValues(value)
          : value
    ));

  return _.isArray(response) ? _.map(response, flattenDataValues) : flattenDataValues(response);
};
Run Code Online (Sandbox Code Playgroud)

用法:

const res = await User.findAll({
  include: [{
    model: Company,
    as: 'companies',
    include: [{
      model: Member,
      as: 'member',
    }],
  }],
});

const plain = toPlain(res);

// 'plain' now contains simple db object without any getters/setters with following structure:
// [{
//   id: 123,
//   name: 'John',
//   companies: [{
//     id: 234,
//     name: 'Google',
//     members: [{
//       id: 345,
//       name: 'Paul',
//     }]
//   }]
// }]
Run Code Online (Sandbox Code Playgroud)


nur*_*zin 9

您可以使用地图功能。这对我有用。

db.Sensors
    .findAll({
        where: { nodeid: node.nodeid }
     })
    .map(el => el.get({ plain: true }))
    .then((rows)=>{
        response.json( rows )
     });
Run Code Online (Sandbox Code Playgroud)


小智 7

我找到了一种使用本机JavaScript函数对嵌套模型和数组运行良好的解决方案。

var results = [{},{},...]; //your result data returned from sequelize query
var jsonString = JSON.stringify(results); //convert to string to remove the sequelize specific meta data

var obj = JSON.parse(jsonString); //to make plain json
// do whatever you want to do with obj as plain json
Run Code Online (Sandbox Code Playgroud)


Amr*_*him 7

对于普通物体

db.model.findAll({
  raw : true ,
  nest : true
})
Run Code Online (Sandbox Code Playgroud)

  • 它不适用于一对多关联,最好使用 .map(obj =&gt; obj.get({ plain: true })) (4认同)