Returning updated object after update to database instead of count

Jevon Cochran :

I am making an update to an entry in a database of food trucks. This is what my model looks like for this particulate update:

function editTruck(changes, id) {
    return db('trucks')
        .where({ id })
        .update(changes)
        .then(id => {
            return findTruckById(id);
        })
}

I want to return the actual updated entry in object form. As you can see above, I tried to accomplish this by drawing on another method in the model called findTruckById. This is what findTruckById looks like:

function findTruckById(id) {
    return db('trucks')
    .select('id', 'name', 'image', 'operator_id', 'cuisine_type', 'physical_address')
    .where({ id })
    .first()
}

This doesn't work because the response returned from the editTruck method is just a count of the entries in the database that were updated, which is 1, as opposed to an id or an array of ids for the entries. Therefore, it always just returns 1 and running 1 inside findTruckById returns an object equivalent to the entry in the trucks database with id 1, which is definitely not what we want. How can I solve this problem?

Jorge Armando Palm :

You already have the ID, you don't need the "update" to return it.

function editTruck(changes, id) {
return db('trucks')
    .where({ id })
    .update(changes)
    .then(() => { // you already have the id, just use the `id` that is already in the scope
        return findTruckById(id);
    })
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32027&siteId=1