Search code examples
postgresqlbookshelf.jsknex.js

How to return and update a table in bookshelf knex


I am using postgresql, knex, and bookshelf to make queries to update my users table. I would like to find all users who didn't sign in during a specific time and then update their numAbsences and numTardies field.

However it appears that when running a raw sql query using bookshelf.knex the result that I get for users is an array of objects rather than an array of bookshelf objects of objects because I can't save the objects directly to the database when I try to use .save(). I get the exception user.save is not a function.

Does anyone know how I can update the values in the database for the users? I've seen the update function but I need to also return the users in absentUsers so I select them currently.

// field indicates whether the student was late or absent
var absentUsers = function(field){
  // returns all users who did not sign in during a specific time
  if (ongoingClasses){
    return bookshelf.knex('users')
      .join('signed_in', 'signed_in.studentId', '=', 'users.id')
      .where('signed_in.signedIn', false)
      .select()
      .then(function(users){
        markAbsent(users, field);
        return users;
      });
  }
}

var markAbsent = function(users, field){
  users.forEach(function(user){
    user[field]++;
    user.save();
  })
}

Solution

  • I've solved my problem by using another sql query in knex. It seemed there was no way to use a sql query and then use standard bookshelf knex methods since the objects returned were not bookshelf wrapper objects.

    var absentUsers = function(field){
      // returns all users who did not sign in during a specific time
      if (ongoingClasses){
        return bookshelf.knex('users')
          .join('signed_in', 'signed_in.studentId', '=', 'users.id')
          .where('signed_in.signedIn', false)
          .select()
          .then(function(users){
            markAbsent(users, field);
          });
      }
    }
    
    var markAbsent = function(users, field){
      users.forEach(function(user){
        var updatedUser = {};
        updatedUser[field] = user[field]+1;
        bookshelf.knex('users')
          .where('users.id', user.id)
          .update(updatedUser).then(function(){
          });
      });
    }