Sequelize default foreign key - postgresql

I have a model Route belongs to Region, when I define the associate, I thought you could just simply do the following:
"use strict";
module.exports = (sequelize, DataTypes) => {
const Route = sequelize.define("Route", {
title: {
type: DataTypes.STRING,
allowNull: false
}
});
Route.associate = models => {
Route.belongsTo(models.Region);
};
return Route;
};
With the route:
app.post("/api/regions/:regionId/routes", routesController.create);
Controller:
create(req, res) {
console.log(req.params.regionId);
return Route.create({
title: req.body.title,
regionId: req.params.regionId
})
.then(route => res.status(201).send(route))
.catch(err => res.status(400).send(err));
},
But when I post to that route, I keeps getting back the route with Null for regionId. Even though I can log the regionId with POST params.
I know the fix is to add foreignKey as following to explicit declare to use regionId as foreignKey:
Route.associate = models => {
Route.belongsTo(models.Region, {
foreignKey: "regionId"
});
};
But I thought it could just default regionId as foreignKey without declaring it. Am I missing something?

Related

Redux toolkit query. useLazyQuery

Try to understand how to structure queries.
What I have now:
File for CRUD:
export const PromoService = apiClient.injectEndpoints({
endpoints: (build) => ({
fetchPromoById: build.query<
Promotion,
{ ppeType: PpeType; id: string }
>({
query: ({ ppeType, id }) => apiQuery(ppeType, 'fetchPromoById', id),
providesTags: (_result, _err) => [{ type: 'Promo' }],
}),
fetchPromoByCategory: build.mutation<
PromotionData,
{ ppeType: PpeType; type: string; bannerId: string }
>({
query: ({ ppeType, type, bannerId }) => ({
url: apiQuery(ppeType, 'fetchPromoByCategory'),
method: 'POST',
body: fetchPromoByCategoryBody(type, bannerId),
}),
invalidatesTags: ['Promo'],
}),
}),
});
export const { useLazyFetchPromoByIdQuery, useFetchPromoByCategoryMutation } =
PromoService;
File for slices:
const initialState: PromotionState = {
chosenPromotion: {} as Promotion,
promoList: [],
};
const promoSlice = createSlice({
name: 'promo',
initialState,
reducers: {
setChosenPromotion: (state, action: PayloadAction<Promotion>) => {
state.chosenPromotion = action.payload;
},
setPromoList: (state, action: PayloadAction<Promotion[]>) => {
state.promoList = action.payload;
},
},
});
Component:
const [fetchPromoByCategory, { isLoading, data: categoryData }] =
useFetchPromoByCategoryMutation({
fixedCacheKey: 'shared-update-promo',
});
const [trigger, result] = useLazyFetchPromoByIdQuery();
const chosenPromo = result.data;
useEffect(() => {
chosenPromo && dispatch(setChosenPromotion(chosenPromo));
}, [chosenPromo]);
There is no problem get data from useMutation in different components skipping the stage of store data via reducer.
Just use fixedCacheKey and it works fine.
Is it possible to use similar approach for getting data in different components with useLazyQuery?
I use additional dispatch to store data from useLazyQuery but I'm sure it's not appropriate approach.
It is perfectly valid to have multiple different query cache entries at once, so useLazyQuery will not initialize to one of them - it will get it's arguments once you call the trigger function.
It looks like you should use useQuery here, sometimes with the skip parameter when you don't want anything fetched from the start.

Mongoose getters are either not working the way I want or I'm misunderstanding what they are

I created some sample code to demonstrate my issue on a smaller scale. From my understanding, a getter function will not affect anything on my database, but when I want to make a get request to view items on my database, it will change the value to whatever is returned only when the data is displayed. However, when I make my get request to view items on my database, the item I am shown is exactly how it was saved. I'm not sure if I'm misunderstanding what a getter function is, or if my syntax is just incorrect somewhere.
Here is my main server:
const express = require('express')
const mongoose = require('mongoose')
// Linking my model
const User = require('./User')
// Initializing express
const app = express()
const PORT = 9999
app.use(express.json())
// Connecting to mongodb
const connectDB = async () => {
try {
await mongoose.connect('mongodb://localhost/testdatabase', {
useUnifiedTopology: true,
useNewUrlParser: true
})
console.log('Connected')
} catch (error) {
console.log('Failed to connect')
}
}
connectDB()
// Creates a new user
app.post('/user/create', async (req, res) => {
await User.create({
name: 'John Cena',
password: 'somepassword'
})
return res.json('User created')
})
// Allows me to view all my users
app.get('/user/view', async (req, res) => {
const findUser = await User.find()
return res.json(findUser)
})
// Running my server
app.listen(PORT, () => {
console.log(`Listening on localhost:${PORT}...`)
})
Here is my model:
const mongoose = require('mongoose')
// My setter - initialPassword is 'somepassword'
// This seems to work properly, in my database the password is changed to 'everyone has the same password here'
const autoChangePassword = (initialPassword) => {
console.log(initialPassword)
return 'everyone has the same password here'
}
// My getter - changedPassword should be 'everyone has the same password here' I think
// The console.log doesn't even run
const passwordReveal = (changedPassword) => {
console.log(changedPassword)
return 'fakehash1234'
}
// Creating my model
const UserSchema = mongoose.Schema({
name: {
type: String
},
password: {
type: String,
set: autoChangePassword,
get: passwordReveal
}
})
// Exporting my model
const model = mongoose.model('user', UserSchema)
module.exports = model
Not sure if it would help anyone since I found my answer on another StackOverflow post, but the issue was I had to set getters to true when converting back to JSON:
// Creating my model
const UserSchema = mongoose.Schema({
name: {
type: String
},
password: {
type: String,
set: autoChangePassword,
get: passwordReveal
}
}, {
toJSON: { getters: true }
})
Any similar problems can be solved by adding some combination of the following:
{
toJSON: {
getters: true,
setters: true
},
toObject: {
getters: true,
setters: true
}
}

Express Sequelize Error - Cannot read property 'findAll' of undefined

I have successfully connected Sequelize and Express using Sequelize's github example with a few changes. I am now trying to do a simple Sequelize query to test the connection, but continue to receive an error stating that the model I have queried is not defined.
// ./models/index.js
...
const sequelize = new Sequelize(process.env.DB, process.env.DB_USER, process.env.DB_PASS, {
host: 'localhost',
dialect: 'postgres'
});
// Test SEQUELIZE connection
sequelize
.authenticate()
.then(() => {
console.log('Database connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
// ./routes/index.js
const models = require('../models');
const express = require('express');
const router = express.Router();
router.get('/contacts', (req, res) => {
models.Contact.findAll().then(contacts => {
console.log("All users:", JSON.stringify(contacts, null, 4));
});
});
module.exports = router;
// ./models/contact.js
const Sequelize = require('sequelize');
var Model = Sequelize.Model;
module.exports = (sequelize, DataTypes) => {
class Contact extends Model {}
Contact.init({
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
}
}, {
sequelize,
modelName: 'contact'
// options
});
return Contact;
};
The error I am getting when using postman to hit /contacts with a GET request is:
[nodemon] starting `node server.js`
The server is now running on port 3000!
Executing (default): SELECT 1+1 AS result
Database connection has been established successfully.
TypeError: Cannot read property 'findAll' of undefined
at router.get (C:\Users\username\desktop\metropolis\metropolis-backend\routes\index.js:6:20)
You are not requiring the model properly.
In ./routes/index.js add the next line:
const Contact = require('./models/contact.js');
And then call Contact.findAll()...
Second approach:
You can gather all your models by importing them into a loader.js file which you will store in the models directory. The whole job of this module is to import the modules together to the same place and then export them from a single place.
It will look something like that:
// loader.js
const modelA = require('./modelA');
const modelB = require('./modelB');
const modelC = require('./modelC');
...
module.exports = {
modelA,
modelB,
modelC,
...
}
And then you can require it in the following way:
in router/index.js:
const Models = require('./models');
const contact = Models.Contact;

Simple Foreign Key Relation with Knex and Bookshelf.js

I'm attempting what should be a simple example of foreign key relations. regions and subregions are separate tables. There is a 1:Many relationship between regions:subregions, where the column region_fk on table subregions is mapped to an id from table regions. Each table also has a name column. The goal is to return the name of the region and the names of all subregions.
The query works fine without the {withRelated: ...} parameter, so something must be amiss with the connection between the models.
knex migration
exports.up = function(knex, Promise) {
return Promise.all([
knex.schema.createTable("regions", function(table) {
table.integer("id").primary();
table.string("name");
}),
knex.schema.createTable("subregions", function(table) {
table.integer("id").primary();
table.string("name");
table
.integer("region_fk")
.references("id")
.inTable("regions");
}),
])
}
bookshelf.config.js
var knex = require("knex")(require("./knexfile.js").development);
var bookshelf = require("bookshelf")(knex);
bookshelf.plugin("registry");
module.exports = bookshelf;
bookshelf models
// Region
const bookshelf = require("../bookshelf.config");
const Region = bookshelf.Model.extend({
tableName: "regions",
subregions: function() {
return this.hasMany("Subregion", "region_fk");
},
});
module.exports = bookshelf.model("Region", Region);
// Subregion
const bookshelf = require("../bookshelf.config");
const Subregion = bookshelf.Model.extend({
tableName: "subregions",
region: function() {
return this.belongsTo("Region", "region_fk");
},
});
module.exports = bookshelf.model("Subregion", Subregion);
Query
const Region = require("../../models/region");
export const getRegionWithId = (req, res) => {
new Region()
.where("id", req.params.id)
.fetch({ withRelated: ["subregions"], require: true })
.then(region => {
res.status(200).json(region);
})
.catch(err => {
res.status(404).json(err);
});
};

Sequelize self association creates extra column

I have the following model defined with Sequelize:
module.exports = function (sequelize, DataTypes) {
var Genre = sequelize.define('Genre', {
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function (models) {
Genre.hasMany(models.Genre, {as: 'subGenre'});
Genre.belongsTo(models.Genre, {as: 'parentGenre'});
}
}
});
return Genre;
}
The idea is that there will be parent genres, and each may have several sub-genres. When I run sync(), the table is created fine, but there is an extra column (GenreId) that I can't quite explain:
"id";"integer";
"name";"character varying";255
"createdAt";"timestamp with time zone";
"updatedAt";"timestamp with time zone";
"GenreId";"integer";
"parentGenreId";"integer";
The sensible way to interpret the model is to only have a parentGenreId column, but I am not sure how to define that bi-directional relationship (genre may have parent, genre may have many children) with only one column being added.
How can I rework the model to allow the relationship to be defined correctly?
I think you could use through (not tested)
module.exports = function (sequelize, DataTypes) {
var Genre = sequelize.define('Genre', {
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function (models) {
Genre.hasMany(models.Genre, {as: 'children', foreignKey: 'ParentId'});
Genre.belongsTo(models.Genre, {as: 'parent', foreignKey: 'ParentId'});
}
}
});
return Genre;
}
So you could have Genre#getChilren and Genre#getParent
EDIT: Due to #mick-hansen, through applies for belongsToMany, not useful for this case. My fault. Corrected using his recommendation