Skip to content

Instantly share code, notes, and snippets.

@andrewjmead
Created March 2, 2016 02:14
Show Gist options
  • Select an option

  • Save andrewjmead/f361ecb6042c48e62258 to your computer and use it in GitHub Desktop.

Select an option

Save andrewjmead/f361ecb6042c48e62258 to your computer and use it in GitHub Desktop.
Keith Composite Index Sequelize
var UserTodos = sequelize.define('UserTodos', {
favorite: {
type: Sequelize.BOOLEAN
},
UserId: {
type: Sequelize.INTEGER,
unique: 'compositeIndex'
},
TodoId: {
type: Sequelize.INTEGER,
unique: 'compositeIndex'
}
});
@keithmichelson
Copy link
Copy Markdown

current Favorite model looks like this:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('favorite', {
    favorite: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        isBoolean: function (value) {
          if (typeof value !== 'number') {
            throw new Error('favorite must be a number');
          }
        }
      }
    }
  });
};

Trying this but I get an unhandled error:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('favorite', {
    favorite: {
      type: DataTypes.INTEGER,
      allowNull: false,
      unique: 'compositeIndex',
      validate: {
        isBoolean: function (value) {
          if (typeof value !== 'number') {
            throw new Error('favorite must be a number');
          }
        }
      }
    },
    userId: {
      type: DataTypes.INTEGER,
      unique: 'compositeIndex'
    }
  });
};

@andrewjmead
Copy link
Copy Markdown
Author

Hey Keith,

Try something like this:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('favorite', {
    favorite: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        isBoolean: function (value) {
          if (typeof value !== 'number') {
            throw new Error('favorite must be a number');
          }
        }
      }
    },
    UserId: {
        type: Sequelize.INTEGER,
        unique: 'compositeIndex'
    },
    TodoId: {
        type: Sequelize.INTEGER,
        unique: 'compositeIndex'
    }
  });
};

@keithmichelson
Copy link
Copy Markdown

`
app.get('/user-todos-favorites', middleware.requireAuthentication, function(req, res) {

var userId = req.user.get('id');

//custom query
db.userFavorites(userId).then(

  function(users) {
    res.json(users);
  },

  function(e) {
    console.log(e);
    res.status(500).send();
  }

);

});
`

Custom query in db.js

db.userFavorites = function(userId) { return db.sequelize.query("select todos.id, todos.mainImage, todos.mainHeading, todos.mainBody, todos.description, todos.createdAt, profiles.firstName, profiles.lastName, profiles.company, profiles.companyImage from todos inner join favorites on favorites.favorite=todos.userId inner join profiles on profiles.userId=favorites.favorite where favorites.userId=" + userId + " order by createdAt", { type: sequelize.QueryTypes.SELECT}); };

@keithmichelson
Copy link
Copy Markdown

original route
`app.post('/favorites/:id', middleware.requireAuthentication, function(req, res){
var favoriteId = parseInt(req.params.id, 10);
var body = {
favoriteId: favoriteId
};

db.favorite.create(body).then(
  function(favorite) {
    req.user.addFavorite(favorite).then(
      function() {
        return favorite.reload();
      }).then(
      function() {
        res.json(favorite.toJSON());
      });
  },
  function(e) {
    res.status(400).json(e);
  });

});`

This will fix the error adding another function to catch the error. But it gives me a database entry with the favorite id and a Null userId. I would think it should add anything.

`app.post('/favorites/:id', middleware.requireAuthentication, function(req, res){
var favoriteId = parseInt(req.params.id, 10);
var body = {
favoriteId: favoriteId
};

db.favorite.create(body).then(
  function(favorite) {
    req.user.addFavorite(favorite).then(
      function() {
        return favorite.reload();
      },
      function(e) {
        console.log(e);
      }).then(
      function() {
        res.json(favorite.toJSON());
      });
  },
  function(e) {
    res.status(400).json(e);
  });

});`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment