I would like to store this JSON into MySQL
{
"tokenId": 1,
"uri": "ipfs://baf...",
"minPrice": {
"type": "BigNumber",
"hex": "0x1a"
},
"signature": "0x288..."
}
My insert code
app.post("/api/create", (req, res) => {
const minPrice = req.body.minPrice;
const uri = req.body.uri;
const tokenId = req.body.tokenId;
const signature = req.body.signature;
db.query("INSERT INTO Details (tokenId,uri,minPrice,signature) VALUES (?,?,?,?)", [tokenId, uri, minPrice, signature], (err, result) => {
if (err) {
console.log(err)
}
console.log(result)
});
})
Error
Error: Column count doesn't match value count at row 1
at Packet.asError (C:\Users\nick_\VSCodeProjects\xxx\nft\node_modules\mysql2\lib\packets\packet.js:728:17)
at Query.execute (C:\Users\nick_\VSCodeProjects\xxx\nft\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\nick_\VSCodeProjects\xxx\nft\node_modules\mysql2\lib\connection.js:487:32)
at PacketParser.onPacket (C:\Users\nick_\VSCodeProjects\xxx\nft\node_modules\mysql2\lib\connection.js:94:12)
at PacketParser.executeStart (C:\Users\nick_\VSCodeProjects\xxx\nft\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\nick_\VSCodeProjects\xxx\nft\node_modules\mysql2\lib\connection.js:101:25)
at Socket.emit (node:events:513: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) {
code: 'ER_WRONG_VALUE_COUNT_ON_ROW',
errno: 1136,
sqlState: '21S01',
sqlMessage: "Column count doesn't match value count at row 1",
sql: "INSERT INTO Details (tokenId,uri,minPrice,signature,) VALUES (10,'ipfs://baf...',`type` = 'BigNumber', `hex` = '0x1a','0x0f...')"
}
My table structure is
id
tokenId int
uri varchar(255)
minPrice json
signature text
I try to console minPrice, this is what it look like
{ type: 'BigNumber', hex: '0x1a' }
You need to use JSON.stringify() to convert the object to JSON.
const minPrice = JSON.stringify(req.body.minPrice);
Related
I have a dynamodb table, with columns as id (partition key) and date. I am trying to update the date where id=2, but I am getting below error as response:
message: "The provided key element does not match the schema"
__type: "com.amazon.coral.validate#ValidationException"
Below is my code:
import * as AWS from 'aws-sdk'
AWS.config.update({
region: 'us-east-1',
accessKeyId: 'MY_ACCESS_KEY',
secretAccessKey: 'MY_SECRET_KEY'
});
const docClient = new AWS.DynamoDB.DocumentClient()
export const updateData = (tableName : any, id : any, date : any) => {
let params = {
TableName: tableName,
Key:{
"id": id
},
UpdateExpression: `set date = :date`,
ExpressionAttributeValues: {":date": date},
};
docClient.update(params, function(err, data) {
if (!err) {
console.log(data);
}else{
console.log(err)
}
})
}
I am calling function like this:
updateData("mytable","2","2023-01-10")
I anyone confirm what I am doing wrong here?
date is a reserved keyword in DynamoDB
You need to use ExpressionAttributeNames param:
let params = {
TableName: tableName,
Key:{
"id": id
},
UpdateExpression: `set #date = :date`,
ExpressionAttributeValues: {":date": date},
ExpressionAttributeNames: {"#date":"date"}
};
As for the exception, ensure that your tables partition key is id and if type String, and that the table does not have a sort key, otherwise you need to add the sort key also.
Server code node.js, express app
app.put('/items/:id', async(req, res) => {
const id = req.params.id;
console.log(id, 'came from id=> app.put');
const qty = req.body;
console.log(qty, 'came from quantity=> app.put');
const filter = {
_id: ObjectId(id)
};
console.log(filter, 'came from filter=> app.put')
const options = {
upsert: true
};
console.log(options, 'came from options=> app.put')
const updatedDoc = {
$set: {
qty: qty,
}
}
console.log(updatedDoc, 'came from updateddoc=> app.put')
const result = await userItems.updateOne(filter, updatedDoc, options);
console.log(result, 'came from result=> app.put')
res.send(result);
})
Client side code
const handleQuantity = event => {
event.preventDefault();
const qty = event.target.qty.value;
console.log(qty);
const url = `http://localhost:4000/items/${id}`
fetch(url, {
method: 'PUT',
body: JSON.stringify({
qty: qty
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then(data => {
console.log(data);
});
}
The error I'm getting:
port 4000 [object Object] came from id=> app.put { qty: '5' } came
from quantity=> app.put D:\web
development\warehouse-management-server-side-pippal5536\node_modules\bson\lib\error.js:41
var _this = _super.call(this, message) || this;
^
BSONTypeError: Argument passed in must be a string of 12 bytes or a
string of 24 hex characters or an integer
at new BSONTypeError (D:\web development\warehouse-management-server-side-pippal5536\node_modules\bson\lib\error.js:41:28)
at new ObjectId (D:\web development\warehouse-management-server-side-pippal5536\node_modules\bson\lib\objectid.js:66:23)
at ObjectId (D:\web development\warehouse-management-server-side-pippal5536\node_modules\bson\lib\objectid.js:26:20)
at D:\web development\warehouse-management-server-side-pippal5536\index.js:73:27
at Layer.handle [as handle_request] (D:\web development\warehouse-management-server-side-pippal5536\node_modules\express\lib\router\layer.js:95:5)
at next (D:\web development\warehouse-management-server-side-pippal5536\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\web development\warehouse-management-server-side-pippal5536\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\web development\warehouse-management-server-side-pippal5536\node_modules\express\lib\router\layer.js:95:5)
at D:\web development\warehouse-management-server-side-pippal5536\node_modules\express\lib\router\index.js:284:15
at param (D:\web development\warehouse-management-server-side-pippal5536\node_modules\express\lib\router\index.js:365:14)
[nodemon] app crashed - waiting for file changes before starting...
If you're looking for what caused the error, it's because the id passed to ObjectID() is invalid.
i am using mongoose to make database for my project, my schema Class has structure like this:
const mongoose = require('mongoose')
const classSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
consultant: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Consultant',
required: true
},
startYear: {
type: String,
required: true
},
classname: {
type: String,
required: true,
unique: true
},
studentList: [
{
code: {
type: String,
required: true
},
fullname: {
type: String,
required: true
}
}
]
})
const Class = mongoose.model('Class', classSchema)
module.exports = Class
as you can see, i have a property called studentList is an array and this is how it was store in mongoose Atlas
so now i want to delete a subdocument in array studentList so this is my route:
http://localhost:5000/users/:code
and this is how i have done:
exports.delele_student_from_user = (req, res, next) => {
var { code } = req.params;
var { classname } = req.body;
User.findOneAndDelete({
classname,
studentList: {
$pull: {
code,
},
},
})
.exec()
.then((doc) => {
console.log(`deleted user with code ${code} from colection User`);
next();
})
.catch((err) => {
console.log(err);
return res.status(500).json({ err });
});
};
and i got this Error:
{ MongoError: unknown operator: $pull
at MessageStream.messageHandler (C:\Users\ASUS\OneDrive\Desktop\uet-backend\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:266:20)
at MessageStream.emit (events.js:198:13)
at processIncomingData (C:\Users\ASUS\OneDrive\Desktop\uet-backend\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
at MessageStream._write (C:\Users\ASUS\OneDrive\Desktop\uet-backend\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
at doWrite (_stream_writable.js:415:12)
at writeOrBuffer (_stream_writable.js:399:5)
at MessageStream.Writable.write (_stream_writable.js:299:11)
at TLSSocket.ondata (_stream_readable.js:709:20)
at TLSSocket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
operationTime:
Timestamp { _bsontype: 'Timestamp', low_: 3, high_: 1603874496 },
ok: 0,
code: 2,
codeName: 'BadValue',
'$clusterTime':
{ clusterTime:
Timestamp { _bsontype: 'Timestamp', low_: 3, high_: 1603874496 },
signature: { hash: [Binary], keyId: [Long] } },
name: 'MongoError' }
DELETE /students/16022267 500 785.904 ms - 240
please show me how to fix this, thank you so much and have a good day
Use findOneAndUpdate()\
You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array.
https://docs.mongodb.com/manual/reference/operator/update/pull/#up._S_pull
You need to use update
exports.delele_student_from_user = async (req, res, next) => {
var { code } = req.params;
var { classname } = req.body;
try {
await User.update(
{ classname },
{
$pull: {
studentList: { code }
}
}
);
return res.status(200).json({ message: "Student deleted" });
} catch (err) {
return res.status(500).json({ err });
}
};
I have also used async / await so it looks cleaner.
'// Issue: Not able to fetch data from table.
// My Code
const sql = require('mssql/msnodesqlv8');
const poolPromise = new sql.ConnectionPool({
driver: 'msnodesqlv8',
server: "test.database.windows.net",
user: "username",
password: "password",
database: 'database',
port: 1433,
})
.connect()
.then((pool: any) => {
console.log('Connected to MSSQL')
return pool
})
.catch((err: any) => console.log('Database Connection Failed! Bad Config: ', err))
;
describe('any test', () => {
it('verification', async () => {
try
{
const pool = await poolPromise;
const result = await pool.request()
.query('select * from table where username = "Protractor"');
console.log(result);
}
catch(err)
{
console.log(err);
}
});
});
Error Occurred:
[13:20:25] I/launcher - Running 1 instances of WebDriver
[13:20:25] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
Started
Connected to MSSQL
{ RequestError: Invalid column name 'Protractor'.
at handleError (C:\Users\automation\node_modules\mssql\lib\msnodesqlv8\request.js:258:21)
at StreamEvents.emit (events.js:189:13)
at errors.forEach.err (C:\Users\automation\node_modules\msnodesqlv8\lib\reader.js:37:20)
at Array.forEach ()
at routeStatementError (C:\Users\automation\node_modules\msnodesqlv8\lib\reader.js:30:14)
at invokeObject.end (C:\Users\automation\node_modules\msnodesqlv8\lib\reader.js:209:11)
at freeStatement (C:\Users\automation\node_modules\msnodesqlv8\lib\driver.js:183:13)
at cppDriver.freeStatement (C:\Users\automation\node_modules\msnodesqlv8\lib\driver.js:163:13) originalError:
{ Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid column name 'Protractor'. sqlstate: '42S22', code: 207 },
name: 'RequestError',
number: 207,
state: '42S22' }
Double and single quotes are not interchangeable in T-SQL.
Try this instead:
const result = await pool.request()
.query(`select * from table where username = 'Protractor'`);
or this:
const result = await pool.request()
.query('select * from table where username = \'Protractor\'');
I am trying to create a temp table and read from it in the same connection using node js and mssql.
Query1: Selects from a bunch of different places and creates
'#mrpSalesHistory'
Query2: Truncates the real table
Query3: Inserts the the data from '#mrpSalesHistory' to the real
table
Query4: Selects count from the real table
Query5: Merges into the real table using '#mrpSalesHistory' as source
Query6: Selects All from real table
Code Snip:
sql.connect(config).then(function() {
new sql.Request().batch(query1, (err, result) => {
if(err){
console.log('Q1');
console.log(err);
}
console.log('Q1');
console.log(result)
})
}).then(function() {
new sql.Request().batch(query2, (err, result) => {
if(err){
console.log('Q2');
console.log(err);
}
console.log('Q2');
console.log(result)
})
}).then(function() {
new sql.Request().batch(query3, (err, result) => {
if(err){
console.log('Q3');
console.log(err);
}
console.log('Q3');
console.log(result)
})
}).then(function() {
new sql.Request().batch(query4, (err, result) => {
if(err){
console.log('Q4');
console.log(err);
}
console.log('Q4');
console.log(result)
})
}).then(function() {
new sql.Request().batch(query5, (err, result) => {
if(err){
console.log('Q5');
console.log(err);
}
console.log('Q5');
console.log(result)
})
}).then(function() {
new sql.Request().batch(query6, (err, result) => {
if(err){
console.log('Q6');
console.log(err);
}
console.log('Q6');
console.log(result)
})
}).catch(function(err) {
console.log(err)
});
After running the following code I get
RequestError: Invalid object name '#mrpSalesHistory'.
on the 3rd and 5th query.
Full log output:
Q3
{ RequestError: Invalid object name '#mrpSalesHistory'.
at StreamEvents.req.once.err (C:\wamp64\www\mrp\updateNode\node_modules\mssql\lib\msnodesqlv8.js:532:17)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at StreamEvents.emit (events.js:211:7)
at routeStatementError (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\reader.js:27:18)
at C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\reader.js:229:15
at Object.cbFreeStatement [as end] (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\driver.js:202:9)
at onInvoke (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\reader.js:228:26)
at onQuery (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\driver.js:114:11)
code: 'EREQUEST',
number: 208,
state: '42S02',
originalError: { Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name '#mrpSalesHistory'. sqlstate: '42S02', code: 208 },
name: 'RequestError' }
Q3
undefined
Q2
{ recordsets: [],
recordset: undefined,
output: {},
rowsAffected: [ -1 ] }
Q5
{ RequestError: Invalid object name '#mrpSalesHistory'.
at StreamEvents.req.once.err (C:\wamp64\www\mrp\updateNode\node_modules\mssql\lib\msnodesqlv8.js:532:17)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at StreamEvents.emit (events.js:211:7)
at routeStatementError (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\reader.js:27:18)
at C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\reader.js:229:15
at Object.cbFreeStatement [as end] (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\driver.js:202:9)
at onInvoke (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\reader.js:228:26)
at onQuery (C:\wamp64\www\mrp\updateNode\node_modules\msnodesqlv8\lib\driver.js:114:11)
code: 'EREQUEST',
number: 208,
state: '42S02',
originalError: { Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name '#mrpSalesHistory'. sqlstate: '42S02', code: 208 },
name: 'RequestError' }
Q5
undefined
Q6
{ recordsets: [ [] ],
recordset: [],
output: {},
rowsAffected: [] }
Q4
{ recordsets: [ [ [Object] ] ],
recordset: [ { '': 0 } ],
output: {},
rowsAffected: [] }
Q1
{ recordsets: [],
recordset: undefined,
output: {},
rowsAffected: [ 77938 ] }
Thank you.
Every one of your new sql.Request().batch( calls should be return new sql.Request().batch(. You're using promises. You have to return the promise in order to actually wait for the promise to be fulfilled. What's really going on in your code is that you're starting all 5 of these sql requests in rapid succession without waiting for any to complete, then their being fullfilled over time with no guaranteed order. Notice the random sequence of output from each query.