Access a single field on Sequelize modelSequelize findall()NodeJs, Mocha and Mongoosenpm WARN package.json: No repository fieldSequelize - how do I partially validate when updating?SequelizeConnectionRefusedError json mysqlQuery concatenated fields in Sequelizefilter fields from response with feathersjsAccess inner join data from sequelize using includeOne To Many Relationship in SequelizeSequelize include with multiple where conditionsequelize (js) association for multiple columns with one table

Can humans ever directly see a few photons at a time? Can a human see a single photon?

Where can I find a database of galactic spectra?

Find the C-factor of a vote

Why do some games show lights shine thorugh walls?

What's currently blocking the construction of the wall between Mexico and the US?

Is my Rep in Stack-Exchange Form?

A STL-like vector implementation in C++

What is the mechanical difference between the Spectator's Create Food and Water action and the Banshee's Undead Nature Trait?

Are all instances of trolls turning to stone ultimately references back to Tolkien?

Require advice on power conservation for backpacking trip

C-152 carb heat on before landing in hot weather?

3D Crossword, Cryptic, Statue View & Maze

Find the diameter of a word graph

Employer wants to use my work email account after I quit

Why do textbooks often include the solutions to odd or even numbered problems but not both?

How do I set an alias to a terminal line?

Wifi dongle speed is slower than advertised

Is it illegal to withhold someone's passport and green card in California?

Is it damaging to turn off a small fridge for two days every week?

Does this Wild Magic result affect the sorcerer or just other creatures?

Swapping rooks in a 4x4 board

How is hair tissue mineral analysis performed?

How to create a Tetrix/Sierpinski Tetrahedron fractal radiating from 0,0,0 ? Python or nodes

Sci fi short story, robot city that nags people about health



Access a single field on Sequelize model


Sequelize findall()NodeJs, Mocha and Mongoosenpm WARN package.json: No repository fieldSequelize - how do I partially validate when updating?SequelizeConnectionRefusedError json mysqlQuery concatenated fields in Sequelizefilter fields from response with feathersjsAccess inner join data from sequelize using includeOne To Many Relationship in SequelizeSequelize include with multiple where conditionsequelize (js) association for multiple columns with one table






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















New to Sequelize. SQlite database created and working. With a sample like this:



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)
)


I get:



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


How can I access one field? By example something like



console.log(users.firstname);


or



console.log(users[firstname]);


didn't work










share|improve this question




























    0















    New to Sequelize. SQlite database created and working. With a sample like this:



    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)
    )


    I get:



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


    How can I access one field? By example something like



    console.log(users.firstname);


    or



    console.log(users[firstname]);


    didn't work










    share|improve this question
























      0












      0








      0








      New to Sequelize. SQlite database created and working. With a sample like this:



      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)
      )


      I get:



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


      How can I access one field? By example something like



      console.log(users.firstname);


      or



      console.log(users[firstname]);


      didn't work










      share|improve this question














      New to Sequelize. SQlite database created and working. With a sample like this:



      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)
      )


      I get:



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


      How can I access one field? By example something like



      console.log(users.firstname);


      or



      console.log(users[firstname]);


      didn't work







      node.js sequelize.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 3:08









      fedetekafedeteka

      3893 silver badges19 bronze badges




      3893 silver badges19 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          There's nothing special about accessing the properties of the objects returned themselves, it's just the users being returned by findAll() is essentially an Array, which you need to iterate in order to return each result:



          let users = await User.findAll();

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



          So you use that when you actually intend to return more than one result. If you mean "one" then you can either find by the Primary Key using findByPk():



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


          Or with query conditions using findOne():



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


          In either case there the object returned is singular and not inside an array as it would be with a method which is expecting to return a list. So the properties are really just accessed as you would expect, as long as you use the correct method to return just one object.



          See the full listings below to how those statements all work within context.



          Modern async/await



          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()


          )()


          Plain Promise Chains



          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());


          Sample output



          Both listings create the same output. Logging has been enabled so you can see the SQL statements being sent to the database engine on for each action:



          "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"





          share|improve this answer























          • Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

            – fedeteka
            Nov 24 '18 at 11:26













          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454841%2faccess-a-single-field-on-sequelize-model%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          There's nothing special about accessing the properties of the objects returned themselves, it's just the users being returned by findAll() is essentially an Array, which you need to iterate in order to return each result:



          let users = await User.findAll();

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



          So you use that when you actually intend to return more than one result. If you mean "one" then you can either find by the Primary Key using findByPk():



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


          Or with query conditions using findOne():



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


          In either case there the object returned is singular and not inside an array as it would be with a method which is expecting to return a list. So the properties are really just accessed as you would expect, as long as you use the correct method to return just one object.



          See the full listings below to how those statements all work within context.



          Modern async/await



          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()


          )()


          Plain Promise Chains



          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());


          Sample output



          Both listings create the same output. Logging has been enabled so you can see the SQL statements being sent to the database engine on for each action:



          "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"





          share|improve this answer























          • Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

            – fedeteka
            Nov 24 '18 at 11:26















          1














          There's nothing special about accessing the properties of the objects returned themselves, it's just the users being returned by findAll() is essentially an Array, which you need to iterate in order to return each result:



          let users = await User.findAll();

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



          So you use that when you actually intend to return more than one result. If you mean "one" then you can either find by the Primary Key using findByPk():



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


          Or with query conditions using findOne():



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


          In either case there the object returned is singular and not inside an array as it would be with a method which is expecting to return a list. So the properties are really just accessed as you would expect, as long as you use the correct method to return just one object.



          See the full listings below to how those statements all work within context.



          Modern async/await



          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()


          )()


          Plain Promise Chains



          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());


          Sample output



          Both listings create the same output. Logging has been enabled so you can see the SQL statements being sent to the database engine on for each action:



          "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"





          share|improve this answer























          • Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

            – fedeteka
            Nov 24 '18 at 11:26













          1












          1








          1







          There's nothing special about accessing the properties of the objects returned themselves, it's just the users being returned by findAll() is essentially an Array, which you need to iterate in order to return each result:



          let users = await User.findAll();

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



          So you use that when you actually intend to return more than one result. If you mean "one" then you can either find by the Primary Key using findByPk():



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


          Or with query conditions using findOne():



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


          In either case there the object returned is singular and not inside an array as it would be with a method which is expecting to return a list. So the properties are really just accessed as you would expect, as long as you use the correct method to return just one object.



          See the full listings below to how those statements all work within context.



          Modern async/await



          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()


          )()


          Plain Promise Chains



          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());


          Sample output



          Both listings create the same output. Logging has been enabled so you can see the SQL statements being sent to the database engine on for each action:



          "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"





          share|improve this answer













          There's nothing special about accessing the properties of the objects returned themselves, it's just the users being returned by findAll() is essentially an Array, which you need to iterate in order to return each result:



          let users = await User.findAll();

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



          So you use that when you actually intend to return more than one result. If you mean "one" then you can either find by the Primary Key using findByPk():



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


          Or with query conditions using findOne():



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


          In either case there the object returned is singular and not inside an array as it would be with a method which is expecting to return a list. So the properties are really just accessed as you would expect, as long as you use the correct method to return just one object.



          See the full listings below to how those statements all work within context.



          Modern async/await



          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()


          )()


          Plain Promise Chains



          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());


          Sample output



          Both listings create the same output. Logging has been enabled so you can see the SQL statements being sent to the database engine on for each action:



          "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"






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 4:22









          Neil LunnNeil Lunn

          104k24 gold badges192 silver badges196 bronze badges




          104k24 gold badges192 silver badges196 bronze badges












          • Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

            – fedeteka
            Nov 24 '18 at 11:26

















          • Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

            – fedeteka
            Nov 24 '18 at 11:26
















          Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

          – fedeteka
          Nov 24 '18 at 11:26





          Thanks, right and very complete answer. On my case for ( let user of users ) log(user.firstname); Worked

          – fedeteka
          Nov 24 '18 at 11:26



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454841%2faccess-a-single-field-on-sequelize-model%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현