creating model in mongoose - node.js

This the schema design from my mysql table, I am trying to migrate to mongodb and I am using mongoose , I am confuse of the datatype to use in creating model for my locators table or collection... I am still new on this mongodb hope you can help me. or is it okay in mongoose to use model without declaring datatype ?
like this
var locatorModel = new Schema({});
Thank you in advance.
CREATE TABLE `locators` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`mch_id` VARCHAR(15) NOT NULL ,
`lat` DOUBLE(10,6) NULL DEFAULT NULL,
`lng` DOUBLE(10,6) NULL DEFAULT NULL,
`latcot` CHAR(1) NULL DEFAULT NULL,
`ttime` TIME NULL DEFAULT NULL,
`tdate` DATE NULL DEFAULT NULL,
`tdatetime` DATETIME NULL DEFAULT NULL,
`velo` DECIMAL(5,2) NULL DEFAULT NULL,
`created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `locators_mch_id_tdatetime_index` (`mch_id`, `tdatetime`),
INDEX `locators_created_at_index` (`created_at`)
)

Related

postgres query explanation

I am making an App where there are message boards and for each board, there is a number of threads and for each thread, there is a number of replies
I need to make a query that gets the threads of a specific board (by board_id) and within each thread, an array of it's replies if no replies for the thread then, get it with an empty replies array
I am not sure if it can be done by a pg query, and it might be achieved by a simple code in the backend modifying the data coming from the query to the format I like but I find a solution currently
here are the tables:
CREATE TABLE threads (
_id SERIAL NOT NULL PRIMARY KEY,
board_id INT NOT NULL REFERENCES board(id),
text VARCHAR(255) NOT NULL,
delete_password VARCHAR(255) NOT NULL,
reported BOOLEAN NOT NULL,
created_on DATE NOT NULL DEFAULT CURRENT_DATE,
bumped_on DATE DEFAULT CURRENT_DATE
);
CREATE TABLE board (
_id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL
);
CREATE TABLE replies (
_id SERIAL PRIMARY KEY NOT NULL,
thread_id INT NOT NULL REFERENCES threads(id),
text VARCHAR(255) NOT NULL,
delete_password VARCHAR(255) NOT NULL,
reported BOOLEAN NOT NULL,
created_on DATE NOT NULL DEFAULT CURRENT_DATE
);

Remove all items in table with Prisma2 and Jest

I would like to know how can I remove all items in table with Prisma2 and Jest ?
I read the CRUD documentation and I try with this :
user.test.js
....
import { PrismaClient } from "#prisma/client"
beforeEach(async () => {
const prisma = new PrismaClient()
await prisma.user.deleteMany({})
})
...
But I have an error :
Invalid `prisma.user.deleteMany()` invocation:
The change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.
My Database
CREATE TABLE User (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
CREATE TABLE Post (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
title VARCHAR(255) NOT NULL,
createdAt TIMESTAMP NOT NULL DEFAULT now(),
content TEXT,
published BOOLEAN NOT NULL DEFAULT false,
fk_user_id INTEGER NOT NULL,
CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE
);
schema.prisma
model Post {
content String?
createdAt DateTime #default(now())
fk_user_id Int
id Int #default(autoincrement()) #id
published Boolean #default(false)
title String
author User #relation(fields: [fk_user_id], references: [id])
##index([fk_user_id], name: "fk_user_id")
}
model User {
email String #unique
id Int #default(autoincrement()) #id
name String?
password String #default("")
Post Post[]
Profile Profile?
}
You are violating the foreign key constraint between Post and User.
You can not remove a User before deleting its Posts
beforeEach(async () => {
const prisma = new PrismaClient()
await prisma.post.deleteMany({where: {...}}) //delete posts first
await prisma.user.deleteMany({})
})
Or set CASCADE deletion on the foreign key,
this way when you delete a User its posts will be automatically deleted
This is another way to do it, this would remove all rows and its dependant rows, also would reset the ids. This way you can iterate over all the tables and order doesn't matter.
prisma.$executeRaw(`TRUNCATE TABLE ${table} RESTART IDENTITY CASCADE;`)

How to structure nested arrays with postgresql

I'm making a simple multiplayer game using postgres as a database (and node as the BE if that helps). I made the table users which contains all of the user accounts, and a table equipped, which contains all of the equipped items a user has. users has a one -> many relationship with equipped.
I'm running into the situation where I need the data from both tables structured like so:
[
{
user_id: 1,
user_data...
equipped: [
{ user_id: 1, item_data... },
...
],
},
{
user_id: 2,
user_data...
equipped: [
{ user_id: 2, item_data... },
...
],
},
]
Is there a way to get this data in a single query? Is it a good idea to get it in a single query?
EDIT: Here's my schemas
CREATE TABLE IF NOT EXISTS users (
user_id SERIAL PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT NOW(),
last_login TIMESTAMP,
authenticated BOOLEAN NOT NULL DEFAULT FALSE,
reset_password_hash UUID
);
CREATE TABLE IF NOT EXISTS equipment (
equipment_id SERIAL PRIMARY KEY NOT NULL,
inventory_id INTEGER NOT NULL REFERENCES inventory (inventory_id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
slot equipment_slot NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT NOW(),
CONSTRAINT only_one_item_per_slot UNIQUE (user_id, slot)
);
Okay so what I was looking for was closer to postgresql json aggregate, but I didn't know what to look for.
Based on my very limited SQL experience, the "classic" way to handle this would just to do a simple JOIN query on the database like so:
SELECT users.username, equipment.slot, equipment.inventory_id
FROM users
LEFT JOIN equipment ON users.user_id = equipment.user_id;
This is nice and simple, but I would need to merge these tables in my server before sending them off.
Thankfully postgres lets you aggregate rows into a JSON array, which is exactly what I needed (thanks #j-spratt). My final* query looks like:
SELECT users.username,
json_agg(json_build_object('slot', equipment.slot, 'inventory_id', equipment.inventory_id))
FROM users
LEFT JOIN equipment ON users.user_id = equipment.user_id
GROUP BY users.username;
Which returns in exactly the format I was looking for.

How to stop Executing (default): DROP TABLE IF EXISTS in sequelize sync

I want to stop sequelize to drop tables this is making difficult for me adding dummy data again again whenever I restart server.
server running on port 3000
Executing (default): DROP TABLE IF EXISTS `teams`;
Executing (default): DROP TABLE IF EXISTS `teams`;
Executing (default): CREATE TABLE IF NOT EXISTS `teams` (`teamId` INTEGER auto_increment , `teamName` VARCHAR(255), `teamEmail` VARCHAR(255), `college` VARCHAR(255), `isPaid` TINYINT(1) NOT NULL DEFAULT false, `isRone` TINYINT(1) NOT NULL DEFAULT false, `isRtwo` TINYINT(1) NOT NULL DEFAULT false, `isRthree` TINYINT(1) NOT NULL DEFAULT false, `isNIT` TINYINT(1) NOT NULL DEFAULT false, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`teamId`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `teams` FROM `startupconclave`
Nice! Database looks fine
Remove {force: true} from your bin/www script in models.sequelize.sync() method.

Sequelize (with Postgres) - Define a new model with engine = postgres

Scenario: I am dealing with a database which is running both postgres and infobright, where infobright is set to default engine.
Goal: Have Sequelize create a table in postgres
Problem: Sequelize is creating table in Infobright by default.
Detailed Explanation:
So when I am trying to define a model which look like:
sequelize.define('mymodel', {
file_name: {
type: Sequelize.STRING,
}
}, {
schema: 'myschema'
});
The sql that get generated looks like:
create
table
if not exists "myschema"."mymodel"(
"id" serial,
"file_name" varchar(255),
"createdAt" timestamp with time zone not null,
"updatedAt" timestamp with time zone not null,
primary key("id")
);
NOTE: Because with (engine = postgres) is missing, the system tries to create table in the default engine i.e. infobright, which is not what I expect it to do.
Expected SQL
create
table
if not exists "myschema"."mymodel"(
"id" serial,
"file_name" varchar(255),
"createdAt" timestamp with time zone not null,
"updatedAt" timestamp with time zone not null,
primary key("id")
) with (
engine = postgres
);
Note: Executing the above generates a table in postgres.
I tried specifying engine in sequelize as well as model configuration, but it doesn't work.
Questions: How shall I configure Sequelize or my model so that it generates the expected sql. Open to other suggestions as well.

Resources