LeftJoinAndMapOne with subquery in typeorm - nestjs

I am new to typeorm and don't know how to handle this.
I need leftJoinAndMapOne with subquery without relationship (Just want to know is this possible or not).
Other question is can I use leftJoinAndMapOne inside leftJoinAndMapOne (nested)?
Can you help me for this?
await this.connection
.getRepository(UserInfoEntity)
.createQueryBuilder('user_info')
.leftJoinAndMapOne(
'user_info.roles',
(qb) => {
return qb.select().from(UserHasOrganizationRoleEntity, 'orgRole');
},
'orgRole',
'orgRole.userId = :userId AND orgRole.organizationId = :organizationId',
{
userId: auth_user.userId,
organizationId: auth_user.organizationId,
},
)
.where('user_info.id = :id', { id })
.getRawMany();
Error:
QueryFailedError: missing FROM-clause entry for table "orgrole"
at new QueryFailedError (/Volumes/Project/Toptipi-node/node_modules/typeorm/error/QueryFailedError.js:11:28)
at PostgresQueryRunner. (/Volumes/Project/Toptipi-node/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:247:31)
at step (/Volumes/Project/Toptipi-node/node_modules/tslib/tslib.js:141:27)
at Object.throw (/Volumes/Project/Toptipi-node/node_modules/tslib/tslib.js:122:57)
at rejected (/Volumes/Project/Toptipi-node/node_modules/tslib/tslib.js:113:69)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
length: 120,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '1192',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3459',
routine: 'errorMissingRTE',
query: 'SELECT "user_info"."id" AS "user_info_id", "user_info"."firstName" AS "user_info_firstName", "user_info"."title" AS "user_info_title", "user_info"."lastName" AS "user_info_lastName", "user_info"."gender" AS "user_info_gender", "user_info"."phoneNumber" AS "user_info_phoneNumber", "user_info"."organizationId" AS "user_info_organizationId", "user_info"."systemRoleId" AS "user_info_systemRoleId", "user_info"."userId" AS "user_info_userId", "user_info"."address" AS "user_info_address", "user_info"."cityId" AS "user_info_cityId", "user_info"."stateId" AS "user_info_stateId", "user_info"."countryId" AS "user_info_countryId", "user_info"."pincode" AS "user_info_pincode", "user_info"."joiningDate" AS "user_info_joiningDate", "user_info"."image" AS "user_info_image", "user_info"."imagePath" AS "user_info_imagePath", "user_info"."experience" AS "user_info_experience", "user_info"."expFile" AS "user_info_expFile", "user_info"."expFilePath" AS "user_info_expFilePath", "user_info"."createdAt" AS "user_info_createdAt", "user_info"."updatedAt" AS "user_info_updatedAt", "orgRole".* FROM "user_info" "user_info" LEFT JOIN (SELECT * FROM "user_has_organization_roles" "orgRole") "orgRole" ON orgRole.userId = $1 AND orgRole.organizationId = $2 WHERE "user_info"."id" = $3',
parameters: [ '2', '1', '14' ]
}

Related

unable to create a relationship with sequelize in postgres

So i wish to create the following 2 tables : user and user_address and have a 1:many relationship among them, i.e a user can have multiple addresses. I followed the sequelize docs and ran the .belongsTo and hasMany on the models of these 2 tables, but i can't seem to query them when i request for a all users with include=[{model:'user_address'}] filter. I wanted to create a scalable system, so i used a somewhat modular approach.
The tables are defined in different files as js objects:
//user.js
const { DataTypes} = require('sequelize');
const name = "user"
const model ={
email : {type:DataTypes.STRING, allowNull:false,unique:true},
password : {type:DataTypes.STRING(16), allowNull:false},
phone : {type:DataTypes.STRING(20), allowNull:true},
name : {type:DataTypes.STRING(50), allowNull:true},
birthday : {type:DataTypes.STRING(50), allowNull:true},
}
const initConfig = {freezeTableName: true}
const getInstance = (email, pwd, phone = null, name = null, dob = null)=>{
return {email: email, password: pwd, phone: phone, name: name, birthday: dob}
}
module.exports = {
name:name,
model:model,
config:initConfig,
getInstance:getInstance
}
//user_address.js
const {DataTypes} = require("sequelize");
const name = "user_address"
const model = {
address : {type:DataTypes.STRING, allowNull:false},
zipcode : {type:DataTypes.INTEGER, allowNull:false},
is_main_address : {type:DataTypes.BOOLEAN, allowNull:false, default:false},
address_alias : {type:DataTypes.STRING, allowNull:true},
address_phone_number : {type:DataTypes.STRING, allowNull:true},
city : {type:DataTypes.STRING, allowNull:true},
}
// user_id : {type:DataTypes.INTEGER, allowNull:true, references: {model: 'user', key: 'id',},}
const config = {
freezeTableName: true
}
module.exports = {
name:name,
model:model,
config:config,
getInstance:()=>{},
}
then we have this ModelKeys.js class that provides an easy access to these model schemas:
const user = require("./user");
const note = require("./note");
const user_address = require('./user_addresses')
module.exports = {
ModelNames:{
USER : user,
USER_ADDRESS: user_address,
NOTE: note,
}
}
then we have this init db class that is supposed to initialise db, define models and run associations on them
const {Sequelize} = require('sequelize');
const {db_creds} = require("../.secrets/db_secrets");
const {ModelNames} = require("./models/model_keys");
const {logDB} = require("../a_commons/logutils");
let db = undefined
async function initTables() {
// create tables
Object.keys(ModelNames).forEach(key=>{
let model = ModelNames[key]
try {
logDB("initialising MODEL=",model==null? "null": `{js_obj : ${model.name}}`)
db.define(model.name,model.model,model.config)
logDB(`model created successfully : ${model.name}` )
}
catch (e) {logError(e)}
})
//sync with dbms
logDB("initialising sync with dbms server...")
await db.sync()
logDB("models synced successfully")
}
function validateTables() {
logDB("all tables are created.","tables=",db.models)
}
async function runAssociations(){
//create associations
logDB("init associations")
let userTable = db.models[ModelNames.USER.name]
let userAddressTable = db.models[ModelNames.USER_ADDRESS.name]
await userTable.hasMany(userAddressTable)
await userAddressTable.belongsTo(userTable)
logDB("associations created successfully")
//sync with dbms
logDB("initialising sync with dbms server...")
await db.sync()
logDB("models synced successfully")
}
module.exports = {
MyDatabase:{
initDB : async () => {
db = new Sequelize(db_creds)
await db
.authenticate()
.then(_ => logDB('Connection established successfully.'))
.then(_ => initTables())
.then(_ => validateTables())
.then(async _ => (await runAssociations()))
.catch(error => logError('Something went wrong', error))
},
getDB: ()=> {
// only useful once initDB is called
return db;
},
getTable : (modelName) => {
// only useful once initDB is called
return db.models[modelName]
}
}
}
if you notice, i did not created any identifier primary keys for my tables but since sequelize automatically generates id key, i was expecting the tables to get created successfully, which they do. during runAssociations() , function, i was also not sure, if it would work since the tables have already been created, and neither table has any reference to them, but i expected this to work.
this whole file runs when someone calls MyDatabase.initDB() and it runs without any errors.
therefore i further created a user_repo.js which looks like this :
const {MyDatabase} = require("./init_db");
const {ModelNames} = require("./models/model_keys");
const {logRepo} = require("../a_commons/logutils");
let userTable = null
module.exports = {
UserRepo: {
initDatabase: async () => {await MyDatabase.initDB()},
init: () => {
userTable = MyDatabase.getTable(ModelNames.USER.name)
logRepo("table initialised. table=",userTable.name)
},
createUser: async (user) => {
await userTable
.create(user)
.then(it => logRepo("user build successfully!", it.toJSON()))
},
getAllUsers: async () => {
let users = await userTable.findAll({include:[{model:MyDatabase.getTable(ModelNames.USER_ADDRESS.name)}]})
logRepo("available users = ", users.map(it=>it.email))
return users
},
getSingleUser: async (email) =>{
return await userTable.findOne(
{where: {email: email}, include:[{model:MyDatabase.getTable(ModelNames.USER_ADDRESS)}]},
)
}
}
}
however, when i run these lines:
const {UserRepo} = require("./user_repo");
const {ModelNames} = require("./models/model_keys");
async function x(){
let repo = UserRepo
await repo.initDatabase()
await repo.init()
await repo.createUser(ModelNames.USER.getInstance("ansh#12345.com","12345678"))
await repo.getAllUsers()
}
x()
1st few lines run perfectly, but for getAllUsers() line ,i get this error :
Executing (default): SELECT "user"."id", "user"."email", "user"."password", "user"."phone", "user"."name", "user"."birthday", "user"."createdAt", "user"."updatedAt", "user_addresses"."id" AS "user_addresses.id", "user_addresses"."address" AS "user_addresses.address", "user_addresses"."zipcode" AS "user_addresses.zipcode", "user_addresses"."is_main_address" AS "user_addresses.is_main_address", "user_addresses"."address_alias" AS "user_addresses.address_alias", "user_addresses"."address_phone_number" AS "user_addresses.address_phone_number", "user_addresses"."city" AS "user_addresses.city", "user_addresses"."createdAt" AS "user_addresses.createdAt", "user_addresses"."updatedAt" AS "user_addresses.updatedAt", "user_addresses"."userId" AS "user_addresses.userId" FROM "user" AS "user" LEFT OUTER JOIN "user_address" AS "user_addresses" ON "user"."id" = "user_addresses"."userId";
node:internal/process/promises:265
triggerUncaughtException(err, true /* fromPromise */);
^
Error
at Query.run (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/sequelize/lib/dialects/postgres/query.js:50:25)
at /Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/sequelize/lib/sequelize.js:314:28
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async PostgresQueryInterface.select (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/sequelize/lib/dialects/abstract/query-interface.js:407:12)
at async Function.findAll (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/sequelize/lib/model.js:1134:21)
at async Object.getAllUsers (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/db/user_repo.js:22:25)
at async x (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/db/test_io.js:101:5) {
name: 'SequelizeDatabaseError',
parent: error: column user_addresses.userId does not exist
at Parser.parseErrorMessage (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 120,
severity: 'ERROR',
code: '42703',
detail: undefined,
hint: undefined,
position: '839',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3643',
routine: 'errorMissingColumn',
sql: 'SELECT "user"."id", "user"."email", "user"."password", "user"."phone", "user"."name", "user"."birthday", "user"."createdAt", "user"."updatedAt", "user_addresses"."id" AS "user_addresses.id", "user_addresses"."address" AS "user_addresses.address", "user_addresses"."zipcode" AS "user_addresses.zipcode", "user_addresses"."is_main_address" AS "user_addresses.is_main_address", "user_addresses"."address_alias" AS "user_addresses.address_alias", "user_addresses"."address_phone_number" AS "user_addresses.address_phone_number", "user_addresses"."city" AS "user_addresses.city", "user_addresses"."createdAt" AS "user_addresses.createdAt", "user_addresses"."updatedAt" AS "user_addresses.updatedAt", "user_addresses"."userId" AS "user_addresses.userId" FROM "user" AS "user" LEFT OUTER JOIN "user_address" AS "user_addresses" ON "user"."id" = "user_addresses"."userId";',
parameters: undefined
},
original: error: column user_addresses.userId does not exist
at Parser.parseErrorMessage (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/anshsachdeva/Downloads/f1_self/f4_web/f4_web_individual_gits/ecommerce/sequalize_tests/notes_db/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 120,
severity: 'ERROR',
code: '42703',
detail: undefined,
hint: undefined,
position: '839',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '3643',
routine: 'errorMissingColumn',
sql: 'SELECT "user"."id", "user"."email", "user"."password", "user"."phone", "user"."name", "user"."birthday", "user"."createdAt", "user"."updatedAt", "user_addresses"."id" AS "user_addresses.id", "user_addresses"."address" AS "user_addresses.address", "user_addresses"."zipcode" AS "user_addresses.zipcode", "user_addresses"."is_main_address" AS "user_addresses.is_main_address", "user_addresses"."address_alias" AS "user_addresses.address_alias", "user_addresses"."address_phone_number" AS "user_addresses.address_phone_number", "user_addresses"."city" AS "user_addresses.city", "user_addresses"."createdAt" AS "user_addresses.createdAt", "user_addresses"."updatedAt" AS "user_addresses.updatedAt", "user_addresses"."userId" AS "user_addresses.userId" FROM "user" AS "user" LEFT OUTER JOIN "user_address" AS "user_addresses" ON "user"."id" = "user_addresses"."userId";',
parameters: undefined
},
sql: 'SELECT "user"."id", "user"."email", "user"."password", "user"."phone", "user"."name", "user"."birthday", "user"."createdAt", "user"."updatedAt", "user_addresses"."id" AS "user_addresses.id", "user_addresses"."address" AS "user_addresses.address", "user_addresses"."zipcode" AS "user_addresses.zipcode", "user_addresses"."is_main_address" AS "user_addresses.is_main_address", "user_addresses"."address_alias" AS "user_addresses.address_alias", "user_addresses"."address_phone_number" AS "user_addresses.address_phone_number", "user_addresses"."city" AS "user_addresses.city", "user_addresses"."createdAt" AS "user_addresses.createdAt", "user_addresses"."updatedAt" AS "user_addresses.updatedAt", "user_addresses"."userId" AS "user_addresses.userId" FROM "user" AS "user" LEFT OUTER JOIN "user_address" AS "user_addresses" ON "user"."id" = "user_addresses"."userId";',
parameters: {}
}
Process finished with exit code 1
Any idea on how to fix this?
You need to register all models and all their associations before calling sync because hasMany/belongsTo only registers associations inside Sequelize models do nothing in DB. Its the responsibility of sync to create the whole structure taking into account all registered models and associations.
await db
.authenticate()
.then(_ => logDB('Connection established successfully.'))
.then(_ => runAssociations())
.then(_ => initTables())
.then(_ => validateTables())
.catch(error => logError('Something went wrong', error))

How to return a value of the most recent document entry in MongoDB

Currently I have a MongoDB with entries that look like this:
{
id: 62f49ecffd9375f8876dffab
channelId: "#username"
stockName: "$USERNAME"
stockPrice: 22
timestamp: "2022-08-11T06:16:47.817Z"
}
located in the database "testDB" and the collection "testColl".
What I am trying to do is find a way to be able to return the value of stockPrice in node.js. Here's the code I'm currently working with:
if(message === "!debug"){
console.log(new MongoClient(process.env.MONGO_URL.concat(channel.toString().substring(1))).db(databaseName).collection(collectionName).find().sort('timestamp').limit(1));
}
where databaseName = "testDB" and collectionName = "testColl". I am quite new with MongoDB so not very familiar with its syntax. Currently when I call this code, I get:
node_modules/tmi.js/lib/logger.js:11
FindCursor {_events: {…}, _eventsCount: 0, _maxListeners: undefined, Symbol(kCapture): false, Symbol(client): MongoClient, …}
_events:
{}
_eventsCount:
0
_maxListeners:
undefined
client:
ƒ client() {\n return this[kClient];\n }
closed:
ƒ closed() {\n return this[kClosed];\n }
cursorOptions:
ƒ cursorOptions() {\n return this[kOptions];\n }
id:
ƒ id() {\n return this[kId];\n }
killed:
ƒ killed() {\n return this[kKilled];\n }
loadBalanced:
ƒ loadBalanced() {\n var _a;\n return !!((_a = this[kClient].topology) === null || _a === void 0 ? void 0 : _a.loadBalanced);\n }
namespace:
ƒ namespace() {\n return this[kNamespace];\n }
readConcern:
ƒ readConcern() {\n return this[kOptions].readConcern;\n }
readPreference:
ƒ readPreference() {\n return this[kOptions].readPreference;\n }
server:
ƒ server() {\n return this[kServer];\n }
session:
ƒ session() {\n return this[kSession];\n }
Symbol(builtOptions):
{raw: false, promoteLongs: true, promoteValues: true, promoteBuffers: false, ignoreUndefined: false, …}
Symbol(client):
MongoClient {_events: {…}, _eventsCount: 0, _maxListeners: undefined, s: {…}, Symbol(kCapture): false, …}
Symbol(closed):
false
Symbol(documents):
(0) []
Symbol(filter):
{}
Symbol(initialized):
false
Symbol(kCapture):
false
Symbol(killed):
false
Symbol(namespace):
MongoDBNamespace {db: 'testDB', collection: 'testColl'}
Symbol(options):
{readPreference: ReadPreference, fieldsAsRaw: {…}, promoteValues: true, promoteBuffers: false, promoteLongs: true, …}
Symbol(session):
ClientSession {_events: {…}, _eventsCount: 1, _maxListeners: undefined, client: MongoClient, sessionPool: ServerSessionPool, …}
Also want to add, I may not need to sort my documents since the entries will always be in chronological order but I was trying to use timestamp to sort by the time the entry was placed.
You've got a lot packed into a single line of code. Let's break your console.log value up into several lines, so we can more easily see what's going on.
const channelName = channel.toString().substring(1);
const url = process.env.MONGO_URL.concat(channelName);
const client = new MongoClient(url);
const db = client.db(databaseName);
const collection = db.collection(collectionName);
const cursor = collection.find().sort('timestamp').limit(1);
You are logging cursor.
Looking at the mongodb API documentation for node.js, it looks like you are missing one or two things.
First, you never actually connect to the server (eg, by calling the connect() method). Now, I'm no mongo expert, and it may be that mongo does some cool just-in-time connect-if-not-connected magic when you call a method that requires a connection. If such magic exists, then this is a red herring.
But, if not, you'll need to add an await client.connect(); line in there.
Second, to get the value out of the cursor, you need to call a cursor method, like next(). This returns a promise, so you'll need to await the promise in order to log the value.
async function getLatestStockPrice(channel, databaseName, collectionName) {
const channelName = channel.toString().substring(1);
const url = process.env.MONGO_URL.concat(channelName);
const client = new MongoClient(url);
await client.connect();
const db = client.db(databaseName);
const collection = db.collection(collectionName);
const cursor = collection.find().sort('timestamp').limit(1);
const item = await cursor.next();
return item.stockPrice;
}

Why am I getting an "invalid Form Body" error on my Discord.js welcome message?

I tried to make a welcome message but I get an error. Does anyone know how to fix this error?
code:
const client = new Client({
allowedMentions: { parse: ["users", "roles", "reaction"]},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.GUILD_WEBHOOKS,
Intents.FLAGS.GUILD_VOICE_STATES,
Intents.FLAGS.GUILD_INVITES,
Intents.FLAGS.GUILD_BANS,
Intents.FLAGS.GUILD_PRESENCES,
]
})
client.on(`guildMemberAdd` , (member, guild) =>{
const arten = [
`Halli Hallo <#!${member.id}>, Willkommen auf dem Teckles.net Server <:T_:788703077184045076>`,
`Willkommen <#!${member.id}>, wir hoffen du hast viel Spaß auf Teckles.net <:T_:788703077184045076>`,
`<#!${member.id}> hat sich dazu entschieden eine Runde mit uns zu spielen <:T_:788703077184045076>`,
]
const welcomemessage = `${arten[Math.floor(Math.random() * arten.length)]}`
let roles = ['781625371682275360', `811351035209056307`, '811351288146821161', '811351128372936704', '828942314046357535']
for (number = 0; number < roles.length; number++) {
let role = member.guild.roles.cache.find(r => r.id === roles[number])
member.roles.add(role)
}
const channel = client.channels.cache.find(channel => channel.id === '916730472950792252')
channel.send({ content: welcomemessage})
})
error:
DiscordAPIError: Invalid Form Body
allowed_mentions.parse[2]: Value must be one of ('roles', 'users', 'everyone').
at RequestHandler.execute (F:\Programmieren\Teckles\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (F:\Programmieren\Teckles\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async TextChannel.send (F:\Programmieren\Teckles\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:172:15) {
method: 'post',
path: '/channels/916730472950792252/messages',
code: 50035,
httpStatus: 400,
requestData: {
json: {
content: 'Halli Hallo <#!777498801349853186>, Willkommen auf dem Teckles.net Server <:T_:788703077184045076>',
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: {
parse: [ 'users', 'roles', 'reaction' ],
replied_user: undefined
},
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
MessageMentionTypes can only be roles, users or everyone. reaction is not compatible with MessageMentionTypes. Remove reaction from client.allowedMentions.parse.

Nodejs Inserting multiple rows into postgres errors on data

I have a script reads data from a json file and inserts them into postgres. Well, that's what it's supposed to do.
The json is read properly and I can see the data as an array in the variables. The connection is made to postgres successfully.
Then I get this error:
syntax error at or near "'{"Archived":"false","ClientEmail":"imaclientcompany#gmail.com","ClientId":52,"ClientName":"Ima Client","DateCreated":1637074825658,"DateSubmitted":1637076927912,"ExternalClientId":"null","Id":"8b9391c0-00af-4710-9481-e0e33ddea546","Practitioner":"bob#jonesperformancecenter.com","PractitionerId":"57b49e3d12cd2f144cebb405","PractitionerName":"Bob Jones","QuestionnaireId":"612524e13ccc040f58dd134e","QuestionnaireName":"PTS Pre Session Form","Status":"Completed"}'" at character 224.
The details of the error:
length: 566,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '224',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1145',
routine: 'scanner_yyerror'
Character 224 is in the middle of the Id field.
The 42601 error is a syntax with no hint or detail. When I google 'scanner_yyerror' all the hits refer to unescaped single quotes. There are no single quotes in the data.
Here is the script:
const pg = require('pg');
const { Pool } = require('pg');
const format = require('pg-format');
const fs = require('fs');
let rawintakes = fs.readFileSync('./data/intakes.json', 'utf8');
let intakes = JSON.parse(rawintakes);
let query1 = format('INSERT INTO intake_summary (Archived, ClientEmail, ClientId, ClientName, DateCreated, DateSubmitted, ExternalClientId, Id, Practitioner, PractitionerId, PractitionerName, QuestionnaireId, QuestionnaireName, Status) VALUES %L returning id', intakes);
async function run() {
let client;
try {
client = new pg.Pool({
connectionString: 'postgres://postres:reallystrongpassword#localhost:5432/cldba01'
});
await client.connect();
let {rows} = await client.query(query1, intakes);
console.log(rows);
} catch (e) {
console.error(e);
} finally {
client.end();
}
}
run();
I can input the same data using SQL without a problem. I have deleted the first record and the same problem occurs on the second one at the same position 224.
I've looked at the query and I don't see a syntax error there either.
Any ideas?
My advice is to use SEQUELIZE instead of SQL , it is far easier and more clear.

Bind message supplies 1 parameters, but prepared statement "" requires 2

I have a database goods with two columns id jsonb primary_key and name.
Using this query:
const query = 'INSERT INTO "goods" (id, name) VALUES ($1, $2)'
together with the following data:
const data = {id: 1, name: "milk"};
gives me the following error:
{ [error: bind message supplies 1 parameters, but prepared statement "" requires 2]
name: 'error',
length: 130,
severity: 'ERROR',
code: '08P01',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'postgres.c',
line: '1556',
routine: 'exec_bind_message' }
I have a postgres database set up, connected via pg.Pool() and executing javascript to insert my data.
Edit:
This is how I prepare my query:
pool.query(query, [data]).then(() => {
console.log("ok")
})
.catch(error => {
console.log(error)
});
Edit2:
Using the following:
const query = 'INSERT INTO "goods" (id, name) VALUES ($1, $2)'
const data = JSON.stringify([1, "milk"]);
pool.query(query, data).then(() => {
console.log("ok")
})
.catch(error => {
console.log(error)
});
Just spits out the following error: [TypeError: self.values.map is not a function]
As per docs, parameters must be JavaScript object (which is array). So you don't need to stringify data
Try this:
const query = 'INSERT INTO goods (id, name) VALUES ($1, $2)'
const data = [1, "milk"];
pool.query(query, data).then(....)
Or
pool.query({
text: 'INSERT INTO goods (id, name) VALUES ($1, $2)',
values: [1, 'milk']
}).then(...)
As per documentation, a Prepared Statement expects an array of values, not an object with properties, i.e. your data must be: const data = [1, "milk"];
I had the same problem using slonik.
Don't use interpolation
Don't do this!
connection.query(sql`
SELECT 1
FROM foo
WHERE bar = ${baz}
`);
Use value placeholders
Do this - wrap variable with single quote
connection.query(sql`
SELECT 1
FROM foo
WHERE bar = ${'baz'}
`);

Resources