-
Notifications
You must be signed in to change notification settings - Fork 643
Closed
Labels
Description
Hi, I'm a bit confused, what is the "correct" way to select fields from result after an insert/update/patch?
// My schema
knex.schema
.createTable('guest', (table) => {
table.increments('id').primary()
table.string('name').notNullable()
table.string('emailAddress')
table.string('nationality')
table.dateTime('createdAt')
table.dateTime('updatedAt')
})
// Inserted data
req.body = {
"name": "Lorem",
"nationality": "RU"
}Desired "guest" object result
GuestModel { name: 'Lorem' }
At first, I tried using returning() as mentioned in the docs (I'm using PostgreSQL)
GuestModel
.query()
.insert(req.body)
.first()
.returning('name')
.then(guest => console.log(guest))Result
GuestModel {
name: 'Lorem',
nationality: 'RU',
createdAt: '2017-03-22T17:34:09.280Z',
updatedAt: '2017-03-22T17:34:09.280Z',
id: 'Lorem' } // ?How come all data get selected? (except nulls)
Using knex's insert without objection.js, it will return just ["Lorem"] without a property name. Why does this behave differently?
So I tried using insertAndFetch()
GuestModel
.query()
.insertAndFetch(req.body)
.select('name')
.then(guest => console.log(guest))Result
GuestModel {
name: 'Lorem',
nationality: 'RU',
createdAt: 2017-03-22T18:27:20.598Z,
updatedAt: 2017-03-22T18:27:20.598Z,
id: 233,
emailAddress: nullAll data selected including nulls. Not sure if select() is allowed there.
This works but requires additional function call
GuestModel
.query()
.insert(req.body)
.then(guest => GuestModel.query().findById(guest.id).select('name'))
.then(guest => console.log(guest))Result
GuestModel { name: 'Lorem' }
Why does returning() behave differently in plain knex? and what is the correct way to do this?