问题
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
回答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"
来源:https://stackoverflow.com/questions/53454841/access-a-single-field-on-sequelize-model