-
-
Save andrewjmead/f361ecb6042c48e62258 to your computer and use it in GitHub Desktop.
| var UserTodos = sequelize.define('UserTodos', { | |
| favorite: { | |
| type: Sequelize.BOOLEAN | |
| }, | |
| UserId: { | |
| type: Sequelize.INTEGER, | |
| unique: 'compositeIndex' | |
| }, | |
| TodoId: { | |
| type: Sequelize.INTEGER, | |
| unique: 'compositeIndex' | |
| } | |
| }); |
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'
}
});
};`
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}); };
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);
});
});`
current Favorite model looks like this:
Trying this but I get an unhandled error: