Sample Header Ad - 728x90

Database Administrators

Q&A for database professionals who wish to improve their database skills

Latest Questions

0 votes
1 answers
378 views
How to parse MongoDB int32 in node.js
I am using MongoDB for a discord bot I am working on, and I want to retrieve a user's balance. My current code is `function findBalance(id){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("DiscordDB"); var query = { uuid: id }; dbo.collection("players").find(query)....
I am using MongoDB for a discord bot I am working on, and I want to retrieve a user's balance. My current code is `function findBalance(id){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("DiscordDB"); var query = { uuid: id }; dbo.collection("players").find(query).toArray(function(err, result) { if (err) throw err; console.log(result.balance); db.close(); }); }); }`. When I call the function it returns undefined... any thoughts?
woofymax (1 rep)
Jun 21, 2020, 06:33 AM • Last activity: Mar 2, 2025, 11:00 AM
0 votes
1 answers
142 views
Is it really possible to use SQL injection to change a database, or is this a scam?
A guy I know at college is claiming he can change his grades by gaining access to the database through an SQL inject, and can also gain access to all admin account privileges and records. The portal is accessed through outlook account and he did a pentest to prove it is vulnerable, ive attached the...
A guy I know at college is claiming he can change his grades by gaining access to the database through an SQL inject, and can also gain access to all admin account privileges and records. The portal is accessed through outlook account and he did a pentest to prove it is vulnerable, ive attached the results. I am new to coding so not sure whether to believe it, is it really possible? from what I believed, the only systems vulnerable to this would be the worst ones, configured by somebody who has never used the database software before, which is extremely unlikely for this college. Are the pentest results real and should be concerned? Is it worth reporting to warn the college? pentest results
Per (11 rep)
Aug 28, 2024, 08:40 PM • Last activity: Aug 29, 2024, 02:41 PM
1 votes
1 answers
55 views
Mongo Preventing access to dangerous command
Reading [Mongo: Definite guide][1]: In first chapter, author mentions the following snippet to change some of the default commands of `db`: ```js var no = function() { print("Not on my watch."); }; // Prevent dropping databases db.dropDatabase = DB.prototype.dropDatabase = no; // Prevent dropping co...
Reading Mongo: Definite guide : In first chapter, author mentions the following snippet to change some of the default commands of db:
var no = function() {
   print("Not on my watch.");
};

// Prevent dropping databases
db.dropDatabase = DB.prototype.dropDatabase = no;

// Prevent dropping collections
DBCollection.prototype.drop = no;

// Prevent dropping an index
DBCollection.prototype.dropIndex = no;

// Prevent dropping indexes
DBCollection.prototype.dropIndexes = no;
I know db is pointing to current database, but my question is from where does DB is coming from?
Cody (123 rep)
Mar 30, 2024, 01:03 PM • Last activity: Apr 1, 2024, 02:49 AM
1 votes
0 answers
583 views
Converting Mongoose schema to Prisma Mysql schema
I am trying to convert the following Mongoose schema to a Prisma MySql Schema. Not sure if I am doing it right. Here is the Mongoose Schema: import mongoose from 'mongoose'; const { ObjectId } = mongoose.Schema; const CartSchema = new mongoose.Schema( { products: [ { product: { type: ObjectId, ref:...
I am trying to convert the following Mongoose schema to a Prisma MySql Schema. Not sure if I am doing it right. Here is the Mongoose Schema: import mongoose from 'mongoose'; const { ObjectId } = mongoose.Schema; const CartSchema = new mongoose.Schema( { products: [ { product: { type: ObjectId, ref: 'Product', }, count: Number, color: String, price: Number, }, ], cartTotal: Number, totalAfterDiscount: Number, orderedBy: { type: ObjectId, ref: 'User' }, }, { timestamps: true } ); export mongoose.models.Cart || mongoose.model('Cart', CartSchema); const CategorySchema = new mongoose.Schema( { name: { type: String, trim: true, required: 'Name is required', minlength: [2, 'Too short'], maxlength: [32, 'Too long'], }, slug: { type: String, unique: true, lowercase: true, index: true, }, }, { timestamps: true } ); export mongoose.models.Category || mongoose.model('Category', CategorySchema); const CouponSchema = new mongoose.Schema( { name: { type: String, trim: true, unique: true, uppercase: true, required: 'Name is required', minlength: [6, 'Too short'], maxlength: [12, 'Too long'], }, expiry: { type: Date, required: true, }, discount: { type: Number, requred: true, }, }, { timestamps: true } ); export mongoose.models.Coupon || mongoose.model('Coupon', CouponSchema); const OrderSchema = new mongoose.Schema( { products: [ { product: { type: ObjectId, ref: 'Product', }, count: Number, color: String, }, ], paymentIntent: {}, orderStatus: { type: String, default: 'Not Processed', enum: [ 'Not Processed', 'Cash On Delivery', 'processing', 'Dispatched', 'Cancelled', 'Completed', ], }, orderedBy: { type: ObjectId, ref: 'User' }, }, { timestamps: true } ); export mongoose.models.Order || mongoose.model('Order', OrderSchema); const ProductSchema = new mongoose.Schema( { title: { type: String, trim: true, required: true, maxlength: 32, text: true, }, slug: { type: String, unique: true, lowercase: true, index: true, }, description: { type: String, required: true, maxlength: 2000, text: true, }, price: { type: Number, required: true, trim: true, maxlength: 32, }, category: { type: ObjectId, ref: 'Category', }, subcategories: [ { type: ObjectId, ref: 'SubCategory', }, ], quantity: Number, sold: { type: Number, default: 0, }, images: { type: Array, }, shipping: { type: String, enum: ['Yes', 'No'], }, color: { type: String, enum: ['Black', 'Brown', 'Silver', 'White', 'Blue'], }, brand: { type: String, enum: ['Apple', 'Samsung', 'Microsoft', 'Lenovo', 'ASUS'], }, ratings: [ { star: Number, postedBy: { type: ObjectId, ref: 'User' }, }, ], }, { timestamps: true, // toJSON: { virtuals: true }, // toObject: { virtuals: true }, } ); export mongoose.models.Product || mongoose.model('Product', ProductSchema); const SubCategorySchema = new mongoose.Schema( { name: { type: String, trim: true, required: 'Name is required', minlength: [2, 'Too short'], maxlength: [32, 'Too long'], }, slug: { type: String, unique: true, lowercase: true, index: true, }, parent: { type: ObjectId, ref: 'Category', required: true }, }, { timestamps: true } ); export mongoose.models.SubCategory || mongoose.model('SubCategory', SubCategorySchema); const UserSchema = new mongoose.Schema( { name: String, email: { type: String, required: true, index: true, }, role: { type: String, default: 'subscriber', }, cart: { type: Array, default: [], }, address: String, wishlist: [{ type: ObjectId, ref: 'Product' }], }, { timestamps: true } ); export mongoose.models.User || mongoose.model('User', UserSchema); Here is what I have got as a result datasource db { provider = "mysql" url = "mysql://user:password@localhost:3306/database_name" } generator client { provider = "prisma-client-js" } model User { id String @id @default(cuid()) name String? email String @unique emailVerified DateTime? cart Cart? address String? wishlist Product[] image String? role Role @default(USER) ratings Rating[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt() } model Cart { id String @id @default(cuid()) products Product[] cartTotal Float? totalAfterDiscount Float? orderedBy User? @relation(fields: [userId], references: [id]) userId String @unique createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } model Category { id String @id @default(cuid()) name String slug String @unique products Product[] subcategories SubCategory[] createdAt DateTime @default(now()) updatedAt DateTime? @updatedAt } model Product { id String @id @default(cuid()) title String slug String @unique description String price Float quantity Int sold Int @default(0) shipping Shipping color Color brand Brand category Category @relation(fields: [categoryId], references: [id]) categoryId String subcategories SubCategory[] carts Cart[] users User[] images Image[] ratings Rating[] createdAt DateTime @default(now()) updatedAt DateTime? @updatedAt @@index([categoryId]) } model SubCategory { id String @id @default(cuid()) name String slug String @unique category Category @relation(fields: [categoryId], references: [id]) categoryId String products Product[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([categoryId]) } enum Role { USER ADMIN } model Image { id String @id @default(uuid()) image String product Product @relation(fields: [productId], references: [id]) productId String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([productId]) } model Rating { id String @id @default(cuid()) star Int postedBy User? @relation(fields: [userId], references: [id]) userId String? product Product? @relation(fields: [productId], references: [id]) productId String? created DateTime @default(now()) updated DateTime @updatedAt @@index([userId]) @@index([productId]) } enum Shipping { Yes No } enum Color { Black Brown Silver White Blue } enum Brand { Apple Samsung Microsoft Lenovo ASUS } Based on the given Mongoose schemas, the relationships between tables can be inferred as follows: User and Cart have a one-to-one relationship, where each Cart is associated with a single User. This is indicated by the orderedBy field in the CartSchema, which references the User model. Category and Product have a one-to-many relationship, where each Category can have multiple Products. This is indicated by the category field in the ProductSchema, which references the Category model. SubCategory and Product have a many-to-many relationship, where each Product can belong to multiple SubCategorys and each SubCategory can have multiple Products. This is indicated by the subcategories field in the ProductSchema, which is an array of references to the SubCategory model. User and Product have a many-to-many relationship, where each User can have multiple Products in their wishlist and each Product can be in multiple users' wishlists. This is indicated by the wishlist field in the UserSchema, which is an array of references to the Product model. Product and Cart have a many-to-many relationship, where each Product can be in multiple Carts and each Cart can have multiple Products. This is indicated by the products field in the CartSchema, which is an array of objects that include a reference to the Product model. Let me know if it makes sense.
John John (111 rep)
Apr 18, 2023, 11:11 PM • Last activity: Apr 19, 2023, 06:07 PM
5 votes
1 answers
21436 views
Not authorized on test to execute command
Here is my code: ``` mongoose.connect(consts.database, { useNewUrlParser: true, useUnifiedTopology: true, sslCA: consts.databaseCert, }); //... const user = await db.userModel.findOne({ username: usernameLowerCase }).exec(); ``` Here is my DB connection string (anonymized): ``` mongodb://myUser:user...
Here is my code:
mongoose.connect(consts.database, {
	useNewUrlParser: true,
	useUnifiedTopology: true,
	sslCA: consts.databaseCert,
});
//...
const user = await db.userModel.findOne({
	username: usernameLowerCase
}).exec();
Here is my DB connection string (anonymized):
mongodb://myUser:userPW@SG-staging-111.servers.mongodirector.com:27017,SG-staging-43334.servers.mongodirector.com:27017?replicaSet=RS-staging-0&ssl=true&authSource=stagingDB
I'm getting this error:
MongoError: not authorized on test to execute command {
	find: "users",
	filter: {
		username: "bob"
	},
	projection: {},
	limit: 1,
	singleBatch: true,
	batchSize: 1,
	returnKey: false,
	showRecordId: false,
	lsid: {
		id: UUID("0a9400e3-83e3-429c-b8c9-92ade2ff210e")
	},
	$clusterTime: {
		clusterTime: Timestamp(1613200171, 1),
		signature: {
			hash: BinData(0, FED473B580D13E7E5073756DB5140981AADB2985),
			keyId: 6928615819992774977
		}
	},
	$db: "test"
}
DB user's info:
myUser	[{"role":"readWrite","db":"stagingDB"}]
I have no clue why I am getting this error not authorized on test to execute command, and in the return string $db: "test" I don't even have a database named test. What could I be doing wrong? I just recently added this new user myUser, but now I'm getting this error. Does this error mean that the user is not authorized to "test" commands? Or, does it mean that I am trying to (somehow) connect with a DB named "test"?
now_world (221 rep)
Feb 13, 2021, 07:31 AM • Last activity: Feb 9, 2023, 05:18 PM
0 votes
1 answers
190 views
Can you run PL/Python or PL/v8 code from the database itself?
It it possible to run code that is stored in the database, on the database. For example, I'd like a trigger to execute a function whose Javascript code is stored in the same database. (Normally, functions are defined in advance.) Is this possible, and if so, how can I do it?
It it possible to run code that is stored in the database, on the database. For example, I'd like a trigger to execute a function whose Javascript code is stored in the same database. (Normally, functions are defined in advance.) Is this possible, and if so, how can I do it?
fadedbee (143 rep)
Jan 13, 2022, 09:59 AM • Last activity: Jan 13, 2022, 10:05 AM
1 votes
1 answers
2807 views
Trouble connecting to local MongoDB server through app.js
I'm a newbie to MongoDB, and I just set up MongoDB within my Ubuntu terminal with mongod and mongo commands running in separate terminals. However, I can't get my app.js that would launch a website to run properly. Here is the beginning of the code: ``` var express = require('express'); var path = r...
I'm a newbie to MongoDB, and I just set up MongoDB within my Ubuntu terminal with mongod and mongo commands running in separate terminals. However, I can't get my app.js that would launch a website to run properly. Here is the beginning of the code:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var helpers = require('handlebars-helpers')();
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var fs = require('fs');
var net = require('net');

process.on('uncaughtException', (err) => {
    console.log(err);
});

//const config = {
//    autoIndex: false,
//    useNewUrlParser: true
//};

//return mongoose.connect(uri, config);

//Log into MongoDB server
//var db = mongoose.connection;
const db = mongoose.connection
const url = 'mongodb://127.0.0.1:27017/modeltest'

mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log('DB Connected!'))
.catch(err => {
console.log('DB Connection Error: ' + err);
});
When I run
app.js
, I get the following error:
{ MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
    at new MongooseError (/home/ubuntu/modeltest/web/node_modules/mongoose/lib/error/mongooseError.js:10:11)
    at NativeConnection.Connection.openUri (/home/ubuntu/modeltest/web/node_modules/mongoose/lib/connection.js:579:11)
    at Mongoose.connect (/home/ubuntu/modeltest/web/node_modules/mongoose/lib/index.js:333:15)
    at Object. (/home/ubuntu/modeltest/web/app.js:31:10)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3
  message: 'The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.',
  name: 'MongooseError' }
ubuntu@ip-172-31-27-34:~/mod
I've also tried to connect to the Mongo Atlas DB I've set up through some modifications to the code:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var helpers = require('handlebars-helpers')();
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var fs = require('fs');
var net = require('net');

process.on('uncaughtException', (err) => {
    console.log(err);
});

//const config = {
//    autoIndex: false,
//    useNewUrlParser: true
//};

//return mongoose.connect(uri, config);

//Log into MongoDB server
var db = mongoose.connection;
//const db = mongoose.connection
//console.log(process.env.MONGO_URI)
const {MongoClient} = require('mongodb');
async function main(){
        const uri = "mongodb+srv://theusernamewhichientered:thepassword@modeltest-3lpoi.mongodb.net/test?retryWrites=true&w=majority"
        const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

try {
    await client.connect();

    await listDatabases(client);

} catch (e) {
    console.error(e);

} finally {
    await client.close();

}
}

main().catch(console.error);

async function listDatabases(client){
    databasesList = await client.db().admin().listDatabases();

    console.log("Databases:");
    databasesList.databases.forEach(db => console.log( - ${db.name}));
};
But I get the following output when I run
app.js
:
DIRNAME
/home/ubuntu/modeltest/web
Server started on port 3000
{ MongoServerSelectionError: connection  to 52.203.196.37:27017 closed
    at Timeout.waitQueueMember.timer.setTimeout [as _onTimeout] (/home/ubuntu/modeltest/web/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
    at ontimeout (timers.js:482:11)
    at tryOnTimeout (timers.js:317:5)
    at Timer.listOnTimeout (timers.js:277:5)
  name: 'MongoServerSelectionError',
  reason: 
   TopologyDescription {
     type: 'ReplicaSetNoPrimary',
     setName: null,
     maxSetVersion: null,
     maxElectionId: null,
     servers: 
      Map {
        'modeltest-shard-00-00-3lpoi.mongodb.net:27017' => [Object],
        'modeltest-shard-00-01-3lpoi.mongodb.net:27017' => [Object],
        'modeltest-shard-00-02-3lpoi.mongodb.net:27017' => [Object] },
     stale: false,
     compatible: true,
     compatibilityError: null,
     logicalSessionTimeoutMinutes: null,
     heartbeatFrequencyMS: 10000,
     localThresholdMS: 15,
     commonWireVersion: null },
What could I do to move past this?
mazuka487 (11 rep)
Apr 29, 2020, 12:10 AM • Last activity: Oct 27, 2021, 06:04 PM
0 votes
0 answers
153 views
Generate report by cross join between two tables
I wanted to generate report between two tables by using CROSS JOIN. Below shows the details of table. Table 1: kod_jawatan |jawatan_id|jawatan_kod|jawatan_nama| |-|-|-| Table 2: tpermohonan |mohon_id|pemohon_id|mohon_tarikh|mohon_tarikhluput |-|-|-|-| Here's the code that I've tried but it didn't wo...
I wanted to generate report between two tables by using CROSS JOIN. Below shows the details of table. Table 1: kod_jawatan |jawatan_id|jawatan_kod|jawatan_nama| |-|-|-| Table 2: tpermohonan |mohon_id|pemohon_id|mohon_tarikh|mohon_tarikhluput |-|-|-|-| Here's the code that I've tried but it didn't work.
SELECT jawatan_nama, MONTHNAME(mohon_tarikh) AS mname,
       count(jawatan_id) AS total
FROM kod_jawatan
CROSS JOIN tpermohonan
WHERE year(mohon_tarikh) = '2019'
GROUP BY MONTH(mohon_tarikh)

UNION ALL

SELECT 'Jumlah',
       count(jawatan_id) AS total
FROM tpermohonan
CROSS JOIN kod_jawatan
WHERE year(mohon_tarikh) = '2019'

This is the output that I want:
|Bil| Jawatan |Jan|Feb|March|April|May|June|July|August|September|Oct|Nov|Dec| Total | |-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-| How do i get the output I want? Much appreciated for your helps.
NAS BS (1 rep)
May 19, 2021, 03:10 AM • Last activity: May 19, 2021, 07:42 PM
0 votes
1 answers
1416 views
Best way for processing over 150 million rows MySql
I wrote a function on nodejs to SELECT 150 million records, process the data and UPDATE those same 150 million records using UPDATE 'table' SET value1='somevalue' WHERE idRo2 = 1; Single Update for each row concatenate send one single query string allowing multipleStatements querys on the db connect...
I wrote a function on nodejs to SELECT 150 million records, process the data and UPDATE those same 150 million records using UPDATE 'table' SET value1='somevalue' WHERE idRo2 = 1; Single Update for each row concatenate send one single query string allowing multipleStatements querys on the db connection. I've being encountering multiple errors as - Error: Connection lost: The server closed the connection. - JavaScript heap out of memory. - RangeError: Invalid string length. - Killed process. I think i might not be using the right technologies or programing technique *Edit: The data process i need to do is to take the 'wholeApiResponse' column value, parse that string and then insert the parsed values into new added columns (askPrice, lastPrice, lowPrice, highPrice, volumePrice, platformTimestamp), this end up modifying the existing row by adding new values from an existing string. enter image description here
Christopher Martinez (107 rep)
Mar 28, 2021, 10:41 PM • Last activity: Mar 29, 2021, 05:27 AM
-1 votes
1 answers
33 views
How to get applied stored procedure for inserted row in mysql php query
``` $query = "CREATE PROCEDURE IF NOT EXISTS Insertion(IN firstname varchar(40),IN lastname varchar(40),IN email varchar(40),IN department varchar(40),IN doj date,IN basicpay int(11)) BEGIN DECLARE HRA decimal(20,2); DECLARE DA decimal(20,2); DECLARE PF decimal(20,2); DECLARE NET_SALARY decimal(20,2...
$query = "CREATE PROCEDURE IF NOT EXISTS Insertion(IN firstname varchar(40),IN lastname varchar(40),IN email varchar(40),IN department varchar(40),IN doj date,IN basicpay int(11))
BEGIN
  
  DECLARE HRA decimal(20,2);
  DECLARE DA decimal(20,2);
  DECLARE PF decimal(20,2);
  DECLARE NET_SALARY decimal(20,2);
  
  IF department = 'HUMAN RESOURCE' THEN
  SET HRA = (5/100)*basicpay;
  SET DA = (7/100)*basicpay;
  SET PF = (10/100)*basicpay;
  
  ELSEIF department = 'MARKETING' THEN
  SET HRA = (5/100)*basicpay;
  SET DA = (7/100)*basicpay;
  SET PF = (10/100)*basicpay;
  
  ELSEIF department = 'PRODUCTION' THEN
  SET HRA = (5/100)*basicpay;
  SET DA = (7/100)*basicpay;
  SET PF = (10/100)*basicpay;
  
  ELSEIF department = 'FINANCE AND ACCOUNTING' THEN
  SET HRA = (5/100)*basicpay;
  SET DA = (7/100)*basicpay;
  SET PF = (10/100)*basicpay;
  
  
  ELSE 
  SET HRA = (5/100)*basicpay;
  SET DA = (7/100)*basicpay;
  SET PF = (10/100)*basicpay;
  
  
  END IF; 
SET NET_SALARY = basicpay+HRA + DA + PF;
	
  insert into employees(FIRST_NAME,LAST_NAME,EMAIL,DEPARTMENT,DATE_OF_JOINING,BASIC_PAY,HRA,DA,PF,NET_SALARY)
  values(firstname,lastname,email,department,doj,basicpay,HRA,DA,PF,NET_SALARY);
  
END";
karthik v (1 rep)
Feb 24, 2021, 12:52 AM • Last activity: Feb 24, 2021, 09:01 AM
1 votes
0 answers
52 views
Non RAM based in-browser database solutions?
I want to decentralize my databases and upload it to [Sia Skynet][1] to give the users the ability to search on front-end. It is important to be able to deal with large amounts of data, but the RAM-based in-browser SQL engines (MiniSearch, AlaSQL, etc) are limited. Yeaterday I made a demo: I sorted...
I want to decentralize my databases and upload it to Sia Skynet to give the users the ability to search on front-end. It is important to be able to deal with large amounts of data, but the RAM-based in-browser SQL engines (MiniSearch, AlaSQL, etc) are limited. Yeaterday I made a demo: I sorted and partitioned my key-value database into 1000 line files and I made an index for the files also. You can try out my demo here , or check it out on GitHub So my question is that are there any better solutions for large-in-browser databases? (I don't really want to reinvent the wheel 😆)
DaWe (119 rep)
Oct 16, 2020, 09:10 AM
0 votes
1 answers
111 views
Migrating timezone timestamps
I am trying to migrate this node library https://github.com/LocalSEOGuide/lighthouse-reporter from Postgres to MySQL and getting an error `error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '2020-03-22T20:38:48.347Z' for column 'fetch_time' at row 1` I've isolated the query where the error h...
I am trying to migrate this node library https://github.com/LocalSEOGuide/lighthouse-reporter from Postgres to MySQL and getting an error error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '2020-03-22T20:38:48.347Z' for column 'fetch_time' at row 1 I've isolated the query where the error happens and built a little test:
await db.query('drop table test');
	 await db.query(`CREATE TABLE IF NOT EXISTS
                  test(
                    id SERIAL PRIMARY KEY,
                    fetch_time datetime
                  );
  	`);

	const query_text = "INSERT INTO test SET ?"
	const query_params = { "fetch_time":"2020-03-22T20:38:48.347Z" }
  	await db.query(query_text, query_params);
It seems that the reporter is returning a timestamp with a Z at the end, but i cant figure out how to get it properly stored in to mysql. Any suggestions would be very helpful! I've also tried with fetch_time as a timestamp
fotoflo (101 rep)
Mar 22, 2020, 09:38 PM • Last activity: Mar 23, 2020, 09:01 AM
Showing page 1 of 12 total questions