访问Sequelize模型上的单个字段

时间:2018-11-24 03:08:35

标签: node.js sequelize.js

续集新手。 SQlite数据库已创建并且正在运行。带有这样的示例:

const Sequelize = require('sequelize')

const sequelize = new Sequelize('sqlite:dbname.db');

sequelize.authenticate()
  .then(() => {
    console.log('Connected')
  })
  .catch(err => {
    console.log('Not connected')
  })

  const User = sequelize.define('users', {
  id: {type: Sequelize.SMALLINT, primaryKey: true},
  firstname: Sequelize.STRING,
  lastname: Sequelize.STRING,
  email: Sequelize.STRING,
  pass: Sequelize.STRING,
})


User.findAll({ attributes: ['firstname', 'lastname', 'email', 'pass'] })
  .then(users => {
    console.log(users);

  })
  .catch(err => {
    console.log(err)
  })

我得到:

Connected [ users {
    dataValues:
     { firstname: 'Jhon',
       lastname: 'Constantine',
       email: 'jhon@constantine.com',
       pass: 'secretpassword' },

如何访问一个字段?例如

console.log(users.firstname);

console.log(users[firstname]);

没有工作

1 个答案:

答案 0 :(得分:1)

访问自己返回的对象的属性没有什么特别的,只是findAll()返回的users实际上是一个Array,您需要对其进行迭代才能返回每个结果:

let users = await User.findAll();

for ( let user of users ) {
  log(`${user.firstname} ${user.email}`);
}

因此,当您实际打算返回多个结果时,可以使用它。如果您的意思是“一个”,则可以使用findByPk()通过主键查找:

let bill = await User.findByPk(1);
log(`${bill.firstname} ${bill.lastname}`);

或者使用findOne()使用查询条件:

let ted = await User.findOne({ where: { firstname: 'Ted' } });
log(`${ted.firstname} ${ted.lastname}`);

在任何一种情况下,返回的对象都是单一的,而不是在数组内部,这与期望返回列表的方法一样。因此,只要您使用正确的方法仅返回一个对象,就可以按预期访问属性。

请参阅下面的完整清单,以了解这些语句如何在上下文中工作。

现代异步/等待

const { Op, SMALLINT, STRING } = Sequelize = require('sequelize');

const logging = log = data => console.log(JSON.stringify(data, undefined, 2));
const sequelize = new Sequelize('sqlite:dbname.db', { logging });

const User = sequelize.define('users', {
  id: { type: SMALLINT, primaryKey: true },
  firstname: STRING(50),
  lastname: STRING(50),
  email: STRING(50),
  pass: STRING(50)
});

(async function() {

  try {

    await sequelize.authenticate();
    await User.sync({ force: true });

    let result = await sequelize.transaction(transaction =>
      Promise.all(
        [
          [1, 'Bill', 'Preston', 'bill.s@stalyns.org', 'password'],
          [2, 'Ted', 'Logan', 'ted.t@styalyns.org', 'secret']
        ].map(([id, firstname, lastname, email, pass]) =>
          User.create({ id, firstname, lastname, email, pass }, { transaction })
        )
      )
    );

    let users = await User.findAll();

    for ( let user of users ) {
      log(`${user.firstname} ${user.email}`);
    }

    let bill = await User.findByPk(1);
    log(`${bill.firstname} ${bill.lastname}`);

    let ted = await User.findOne({ where: { firstname: 'Ted' } });
    log(`${ted.firstname} ${ted.lastname}`);

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

平原承诺链

const { Op, SMALLINT, STRING } = Sequelize = require('sequelize');

const logging = log = data => console.log(JSON.stringify(data, undefined, 2));
const sequelize = new Sequelize('sqlite:dbname.db', { logging });

const User = sequelize.define('users', {
  id: { type: SMALLINT, primaryKey: true },
  firstname: STRING(50),
  lastname: STRING(50),
  email: STRING(50),
  pass: STRING(50)
});


sequelize.authenticate()
  .then(() => User.sync({ force: true }) )
  .then(() => sequelize.transaction(transaction =>
    Promise.all(
      [
        [1, 'Bill', 'Preston', 'bill.s@stalyns.org', 'password'],
        [2, 'Ted', 'Logan', 'ted.t@styalyns.org', 'secret']
      ].map(([id, firstname, lastname, email, pass]) =>
        User.create({ id, firstname, lastname, email, pass }, { transaction })
      )
    )
  ))
  .then(() => User.findAll() )
  .then(users => {
    for ( let user of users ) {
      log(`${user.firstname} ${user.email}`);
    }
  })
  .then(() => User.findByPk(1) )
  .then(bill => log(`${bill.firstname} ${bill.lastname}`) )
  .then(() => User.findOne({ where: { firstname: 'Ted' } }) )
  .then(ted => log(`${ted.firstname} ${ted.lastname}`) )
  .catch(console.error)
  .then(() => process.exit());

样本输出

两个清单都创建相同的输出。已启用日志记录,因此您可以看到每个操作的SQL语句都已发送到数据库引擎:

"Executing (default): SELECT 1+1 AS result"
"Executing (default): DROP TABLE IF EXISTS `users`;"
"Executing (default): CREATE TABLE IF NOT EXISTS `users` (`id` SMALLINT PRIMARY KEY, `firstname` VARCHAR(50), `lastname` VARCHAR(50), `email` VARCHAR(50), `pass` VARCHAR(50), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);"
"Executing (default): PRAGMA INDEX_LIST(`users`)"
"Executing (default): PRAGMA INDEX_INFO(`sqlite_autoindex_users_1`)"
"Executing (9218ce2c-7c99-4b3a-ac48-9ae5f1d832d4): BEGIN DEFERRED TRANSACTION;"
"Executing (9218ce2c-7c99-4b3a-ac48-9ae5f1d832d4): INSERT INTO `users` (`id`,`firstname`,`lastname`,`email`,`pass`,`createdAt`,`updatedAt`) VALUES (1,'Bill','Preston','bill.s@stalyns.org','password','2018-11-24 04:09:00.628 +00:00','2018-11-24 04:09:00.628 +00:00');"
"Executing (9218ce2c-7c99-4b3a-ac48-9ae5f1d832d4): INSERT INTO `users` (`id`,`firstname`,`lastname`,`email`,`pass`,`createdAt`,`updatedAt`) VALUES (2,'Ted','Logan','ted.t@styalyns.org','secret','2018-11-24 04:09:00.629 +00:00','2018-11-24 04:09:00.629 +00:00');"
"Executing (9218ce2c-7c99-4b3a-ac48-9ae5f1d832d4): COMMIT;"
"Executing (default): SELECT `id`, `firstname`, `lastname`, `email`, `pass`, `createdAt`, `updatedAt` FROM `users` AS `users`;"
"Bill bill.s@stalyns.org"
"Ted ted.t@styalyns.org"
"Executing (default): SELECT `id`, `firstname`, `lastname`, `email`, `pass`, `createdAt`, `updatedAt` FROM `users` AS `users` WHERE `users`.`id` = 1;"
"Bill Preston"
"Executing (default): SELECT `id`, `firstname`, `lastname`, `email`, `pass`, `createdAt`, `updatedAt` FROM `users` AS `users` WHERE `users`.`firstname` = 'Ted' LIMIT 1;"
"Ted Logan"