How to write a RealmList in a node realm schema - node.js

I have a schema for OrderEntry which has a RealmList of another realm object ItemEntry:
export const OrderEntrySchema: Realm.ObjectSchema = {
name: 'OrderEntry',
primaryKey: '_id',
properties: {
...
items: ???
}
}
export const ItemEntrySchema: Realm.ObjectSchema = {
name: 'ItemEntry',
primaryKey: 'id',
properties: {
...
}
}
How to define item as a RealmList<ItemEntry> as can be done in android?
Note: Both schemas are in separate files.

You can specify a list of ItemEntry like this
items: {type: 'list', objectType: 'ItemEntry'}
Here is an example with your schemas.
const OrderEntrySchema = {
name: 'OrderEntry',
primaryKey: 'id',
properties: {
id: 'string',
items: {type: 'list', objectType: 'ItemEntry'}
}
};
const ItemEntrySchema = {
name: 'ItemEntry',
primaryKey: 'id',
properties: {
id: 'string'
}
};
If you want to put them in separate files, you will need to import ItemEntry in the file with OrderEntry

Related

Sequelize TypeError: Cannot read properties of undefined (reading 'replace')

Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Characters' AND TABLE_SCHEMA = 'dev'
D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\utils.js:364
return s.replace(new RegExp(tickChar, 'g'), '');
^
TypeError: Cannot read properties of undefined (reading 'replace')
at Object.removeTicks (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\utils.js:364:12)
at MySQLQueryGenerator.quoteIdentifier [as _quoteIdentifier] (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\mysql\query-generator.js:590:33)
at MySQLQueryGenerator.quoteIdentifier (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\abstract\query-generator.js:954:19)
at MySQLQueryGenerator.quoteTable (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\abstract\query-generator.js:1037:20)
at MySQLQueryGenerator.attributeToSQL (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\mysql\query-generator.js:416:39)
at MySQLQueryGenerator.attributesToSQL (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\mysql\query-generator.js:441:45)
at MySQLQueryInterface.createTable (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\dialects\abstract\query-interface.js:222:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Function.sync (D:\GDrive\dev\hanghae\실전\dev\node_modules\sequelize\src\model.js:1353:7)
While creating a new table, I'm having this error.
All referenced types are fine. userId in Users is defined as MEDIUMINT.UNSIGNED, titleId and fieldId as TINYINT.UNSIGNED
I can't see any typos nor can find any similar issue from others.
Does anybody have an idea, please?
below is my charater model code
import sequelize from '../config/connection';
import { Fields, Titles, Users } from '../models';
import {
Model, DataTypes,
InferAttributes, InferCreationAttributes,
CreationOptional, ForeignKey
} from 'sequelize'
class Characters extends Model<
InferAttributes<Characters>, InferCreationAttributes<Characters>
>{
declare characterId: CreationOptional<number>;
declare userId: ForeignKey<number>;
declare titleId: ForeignKey<number>;
declare fieldId: ForeignKey<number>;
declare name: string;
declare job: string;
declare level: number;
declare attack: number;
declare defense: number;
declare hit: number;
declare mana: number;
declare exp: number;
declare createdAt: CreationOptional<number>;
declare updatedAt: CreationOptional<number>;
// declare User: NonAttribute<Users>
// declare Title: NonAttribute<>;
// declare Field: NonAttribute<>;
};
Characters.init({
characterId: {
type: DataTypes.MEDIUMINT.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
userId: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false,
references: {
model: Users,
key: 'userId'
}
},
titleId: {
type: DataTypes.TINYINT.UNSIGNED,
allowNull: false,
references: {
model: Titles,
key: 'titleId'
}
},
fieldId: {
type: DataTypes.TINYINT.UNSIGNED,
allowNull: false,
references: {
model: Fields,
key: 'fieldId'
}
},
name: {
type: DataTypes.STRING(40),
allowNull: false,
unique: true
},
job: {
type: DataTypes.STRING(40),
allowNull: false
},
level: {
type: DataTypes.TINYINT.UNSIGNED,
allowNull: false
},
attack: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
defense: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
hit: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
mana: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
exp: {
type: DataTypes.MEDIUMINT.UNSIGNED,
allowNull: false
},
createdAt: {
type: DataTypes.INTEGER,
defaultValue: (Date.now()/1000)|0 + 60 * 60 * 9
},
updatedAt: {
type: DataTypes.INTEGER,
defaultValue: (Date.now()/1000)|0 + 60 * 60 * 9
}
}, {
sequelize,
modelName: 'Characters'
});
export default Characters;
The problem is that maybe your tables were not created/synced with the sequelize instance
I had the same issue and when I synced my database connection the problem was solved. Thats why maybe when you created the file again, it worked
Update 1/10/2022:
Here's an axemple of my code:
// your sequelize instance connected with your database
const sequelize = await new Sequelize({
dialect: 'foo',
storage: 'bar'
});
// initialization of your models...
YourModel.init(
{
foo: {
type: DataTypes.STRING(128),
allowNull: true
}
},
{
sequelize,
tableName: 'bar',
timestamps: true
}
);
...
// and then: synchronize the sequelize instance with your database and the needed data for sequelize to properly work will be available
await sequelize.sync();
Also check the official documentation for reference: https://sequelize.org/docs/v6/core-concepts/model-basics/#model-synchronization

Sequelize Model Relationships

I have 2 models and what I am trying to do is when a match is created, it will automatically create a match report. here is the code:
Match.js
const Sequelize = require('sequelize');
const db = require('../config/database');
const Match = db.define('matches',{
id: {
type: Sequelize.INTEGER(10).UNSIGNED,
autoIncrement: true,
primaryKey: true
},
type: {
type: Sequelize.STRING,
defaultValue: 'main' //match type either Main or Sub
},
game_grp: {
type: Sequelize.SMALLINT(6),
defaultValue: null // belongs to main match side bet.
},
sub_type: {
type: Sequelize.STRING,
defaultValue: null //values: (other = 1stBlood,F10k), (main = MatchWinner), (handicap = Match Handicap)
},
name: {
type: Sequelize.STRING,
defaultValue: null
},
league_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'League', //leagues has many matches
key: 'id'
}
},
},
);
Match.associate = models => {
Match.hasMany(models.MatchReport, {
foreignKey: 'id'
});
};
module.exports = Match;
MatchReport.js
const Sequelize = require('sequelize');
const db = require('../config/database');
const MatchReport = db.define('match_reports',
{
id: {
type: Sequelize.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
references: {
model: 'Match', //MatchReport's ID belongs to matches'
key: 'id'
}
},
league_id: {
type: Sequelize.INTEGER,
defaultValue: 0,
references: {
model: 'Match',
key: 'league_id'
}
},
name: {
type: Sequelize.STRING,
defaultValue: null
},
status: {
type: Sequelize.STRING,
defaultValue: null //ongoing,draw,cancelled,open
},
);
module.exports = MatchReport;
I'm new to node.js and sequelize.js model relationships so it's quite hard to understand some of the documentation's details.
Any ideas on how to deal with this? TYIA
First, you have a problem with MatchReport definition:
It needs to have its own id as PK and not as FQ.
MatchReport.league_id is referencing to Match.league_id, so if you'll point to a Match instance it's redundant, right? So, let's point to Match instance instead.
Define your MatchReport as follows:
const Sequelize = require('sequelize');
const db = require('../config/database');
const MatchReport = db.define('match_reports',
{
id: {
type: Sequelize.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
match_id: {
type: Sequelize.INTEGER(10).UNSIGNED,
references: {
model: 'Match',
key: 'id'
}
},
name: {
type: Sequelize.STRING,
defaultValue: null
},
status: {
type: Sequelize.STRING,
defaultValue: null //ongoing,draw,cancelled,open
},
);
module.exports = MatchReport;
Now, there are some options to create MatchReport instance when a Match is created.
1) Put the logic inside a function that creates a match.
async function createMatch(match) {
// match is the object you want to insert.
var newMatch = await Match.create(data);
var newMatchReport = await MatchReport.create({
match_id: newMatch.id,
name: ...,
status: ...., //
});
}
2) Use the include option of sequelize.
async function createMatch(match) {
// match is the object you want to insert.
var newMatch = await Match.create(data, {
include: [{ model: MatchReport}]
});
}
Pay attention to the following points as well:
1) When creating an instance of a model the whole instance returns and not only the data. The data itself could be found under dataValues object.
2) You need to apply the associations between the models as follows:
In your Match model:
let MatchReport = require('./MatchReport');
Match.hasOne(MatchReport);
In your MatchReport model:
let Match = require('./Match');
MatchReport.belongsTo(Match);

Writing into a nested schema for Realm

Based on my api response I made my schema for realm but I'm not able to push values into realm according to schema. plase let me know is there any way to do like this
export const WORKFLOW_SCHEMA = 'work_flow';
export const WORKFLOW_NAMES_SCHEMA = 'workflow_name';
export const WorkflowNamesSchema = {
name: WORKFLOW_SCHEMA,
primaryKey :'workflow_Name',
properties: {
workflow_Name: 'string',
default_State: 'int',
states: { type: 'list', objectType: WORKFLOW_NAMES_SCHEMA }
}
};
export const NEXTSTATE_SCHEMA = 'next_states';
export const WorkFlowSchema = {
name: WORKFLOW_NAMES_SCHEMA,
primaryKey :'state_ID',
properties: {
state_ID: 'int',
action_Name: 'string',
state: 'string',
next_States: { type: 'list', objectType: NEXTSTATE_SCHEMA }
}
};
export const NextStatesSchema = {
name: NEXTSTATE_SCHEMA,
properties: {
action: 'string',
state: 'string',
},
};

Sequelize, GraphJS : Cannot read property '2' of null

I'm using GraphJS with sequelize, when I defined a unique column in the model:
const Product = Connection.define('Product', {
label: {
type: Sequelize.STRING,
allowNull: false,
unique: true <--------------
},
description: {
type: Sequelize.TEXT,
allowNull: false
},
price: {
type: Sequelize.FLOAT(6, 3),
}
});
when I try to insert the second row with the same label :
const Mutations = new GraphQLObjectType({
name: 'Mutations',
description: 'All Mutations',
fields: () => {
return {
addProduct: {
type: Product,
args: {
new: {
name: 'New product',
type: ProductInput
}
},
resolve(_, args) {
return Db.models.Product.create(args.new);
}
},
};
}
});
I got the following error:
TypeError: Cannot read property '2' of null
Any ideas ?
you dont seem to be the only one having the problem:
https://github.com/sequelize/sequelize/issues/6725
https://github.com/feathersjs-ecosystem/feathers-sequelize/issues/71
do you also use mysql, and if yes which version?
seems to work in some versions, and in some not:
https://github.com/feathersjs-ecosystem/feathers-sequelize/issues/71#issuecomment-255192417

How to make a sub query (or join) in GraphQl?

I am trying to wrap my head around GraphQl, more precisely on sub queries.
I have two tables: Products and Likes, the two have a common "userId" column. How could I count the total number of likes for each product from the Likes table based on the common column?
schema:
import { makeExecutableSchema } from 'graphql-tools';
import resolvers from './resolvers';
const schema = `
type Products {
id: Int!
name: String
userid: String
}
type Likes {
id: Int!
userid: String
}
# the schema allows the following query:
type Query {
products: [Products]
}
`;
export default makeExecutableSchema({
typeDefs: schema,
resolvers,
});
resolver:
import { Products, Likes } from './connection.js';
const resolveFunctions = {
Query: {
likes() {
return Likes.findAll();
},
products() {
return Products.findAll();
},
},
};
export default resolveFunctions;
connection.js
...
const Products = db.define('products', {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
name: Sequelize.STRING,
userid: Sequelize.STRING,
title: Sequelize.STRING,
},
{
timestamps: false
}
);
const Likes = db.define('likes', {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
userid: Sequelize.STRING
},
{
timestamps: false
}
);
export { Products, Likes };

Resources