In my postgres users table, I have a column 'followers' that holds a number. I am trying to call a PATCH request to increment the value of followers by 1 in the row that corresponds to the username that I pass into my api. However, my postman returns Cannot PATCH when testing my call. Here is the call:
app.patch('/api/incfollowers/:username',async(req,res)=>{
try {
const {username} = req.params
const updateVals = await pool.query(
"UPDATE users SET followers = followers + 1 WHERE username = $1",[username]
)
} catch (error) {
console.error(error.message)
}
})
Related
It seems quite new, but just hoping someone here has been able to use nodejs to write directly to BigQuery storage using #google-cloud/bigquery-storage.
There is an explanation of how the overall backend API works and how to write a collection of rows atomically using BigQuery Write API but no such documentation for nodejs yet. A recent release 2.7.0 documents the addition of said feature but there is no documentation, and the code is not easily understood.
There is an open issue requesting an example but thought I'd try my luck to see if anyone has been able to use this API yet.
Suppose you have a BigQuery table called student with three columns id,name and age. Following steps will get you to load data into the table with nodejs storage write api.
Define student.proto file as follows
syntax = "proto2";
message Student {
required int64 id = 1;
optional string name = 2;
optional int64 age = 3;
}
Run the following at the command prompt
protoc --js_out=import_style=commonjs,binary:. student.proto
It should generate student_pb.js file in the current directory.
Write the following js code in the current directory and run it
const {BigQueryWriteClient} = require('#google-cloud/bigquery-storage').v1;
const st = require('./student_pb.js')
const type = require('#google-cloud/bigquery-storage').protos.google.protobuf.FieldDescriptorProto.Type
const mode = require('#google-cloud/bigquery-storage').protos.google.cloud.bigquery.storage.v1.WriteStream.Type
const storageClient = new BigQueryWriteClient();
const parent = `projects/${project}/datasets/${dataset}/tables/student`
var writeStream = {type: mode.PENDING}
var student = new st.Student()
var protoDescriptor = {}
protoDescriptor.name = 'student'
protoDescriptor.field = [{'name':'id','number':1,'type':type.TYPE_INT64},{'name':'name','number':2,'type':type.TYPE_STRING},{'name':'age','number':3,'type':type.TYPE_INT64}]
async function run() {
try {
var request = {
parent,
writeStream
}
var response = await storageClient.createWriteStream(request);
writeStream = response[0].name
var serializedRows = []
//Row 1
student.setId(1)
student.setName('st1')
student.setAge(15)
serializedRows.push(student.serializeBinary())
//Row 2
student.setId(2)
student.setName('st2')
student.setAge(15)
serializedRows.push(student.serializeBinary())
var protoRows = {
serializedRows
}
var proto_data = {
writerSchema: {protoDescriptor},
rows: protoRows
}
// Construct request
request = {
writeStream,
protoRows: proto_data
};
// Insert rows
const stream = await storageClient.appendRows();
stream.on('data', response => {
console.log(response);
});
stream.on('error', err => {
throw err;
});
stream.on('end', async () => {
/* API call completed */
try {
var response = await storageClient.finalizeWriteStream({name: writeStream})
response = await storageClient.batchCommitWriteStreams({parent,writeStreams: [writeStream]})
}
catch(err) {
console.log(err)
}
});
stream.write(request);
stream.end();
}
catch(err) {
console.log(err)
}
}
run();
Make sure your environment variables are set correctly to point to the file containing google cloud credentials.
Change project and dataset values accordingly.
Hello I'm trying to take data from a sql table but the data that I want to check is into an array, so I need compare the data to check if an user is into the group, the array only have the IDs from users and the specific ID that I want is being bringing to me through the login.
This code is in Typescript.
If you need more information let me know please.
class CompanyController {
async consultCompanys(req: Request, res: Response) {
let response: ResponseModel = new ResponseModel(ECodeResponse.Ok, "", []);
const { UserId } = req.body;
try {
const Companies: any = await pool.query(
`SELECT (CompanyId) From Companies Where Members = '${UserId}'`
);
response.Code = ECodeResponse.Ok;
response.Message = EWarningMessage.Error;
return res.json(response);
} catch (error) {
response.Code = ECodeResponse.Warning;
response.Message = EWarningMessage.Error;
return res.json(response);
}
}
}
I'm a litle oxidated in this kind of consults
I currently have a database of people with each individual person and they hold a status value. I am trying to change their status value.
const id = parseInt(req.params.id , 10);
const { valid, messageObj } = validateId(id);
if (!valid) {
res.status(400).send(messageObj);
}
let { status, priority } = req.body;
let people = db.prepare('select * from people').all();
const person = people.find(person => person.id === id);
if(status !== 'none' & status == 'ready' || status == 'done'){
let updates = db.query(
'UPDATE people SET ? WHERE ?',
[{ status: status }, { id: id }]
);
}
I keep getting an error of db.query is not a function but I get that for every function that I try.
Pretty new to SQL but just trying to figure this out or any documentation that will help me as the better-sqlite3 doesn't have any update functions in the official documentation.
I cannot find a function called query() in the better-sqlite3 API for the Database class. I think that you would need to prepare() a Statement object, then run() it.
Also, column names cannot be passed as bound parameters. Your query should look like:
UPDATE people SET status = ? WHERE name = ?
You would need to change this:
let updates =
db.query('UPDATE people SET ? WHERE ?', [{ status: status }, { id: id }]);
To:
const stmt = db.prepare('UPDATE people SET status = ? WHERE id = ?');
const updates = stmt.run(status, id);
According to templates you can use javascript syntax to replace variables to its value.
let updates = db.exec(`UPDATE people SET status='${status}' WHERE id='${id}'`);
I have employee in one sheet and I get row id of the searched employee on the page now I want to update the same record with the row id so that my time of searching the employee is saved. Is there any way to do this?
function getEmployeeName_(){
try{
var username = getUserName_();
var formObject = {verb:'GET',url:'/Employees?Emp_Email='+g_obj.current_user_email};
var response_obj = processForm(formObject);
response_obj = JSON.parse(response_obj);
var userObj = {};
if(response_obj != undefined && response_obj.status != undefined && response_obj.status == 'success'){
if(response_obj['data'].length >0){
userObj = response_obj['data'][0];
}
}
return userObj.Emp_Name;
}catch(e){
Logger.log(e.message);
return { status: 'error', message: 'Something went wrong while fetching User Name.'};
}
}
To update values in Sheets API, use spreadsheets.values.update. The rowId you're talking about will be a part of range property using A1Notation.
To check samples on using sheets values.update, check Sheet Operations.
I want to connect to Azure SQL Database using node.js. I found a documentation in MSDN blog and see I directly use their source code to connect. I have entered the correct credentials and successfully connected to the database.
However, when I execute the query, it says invalid object name, my table is dbo.Users. What is the problem?
var Connection = require('tedious').Connection;
var config = {
userName: 'myusername',
password: 'mypw',
server: 'myserver',
// When you connect to Azure SQL Database, you need these next options.
options: { encrypt: true, database: 'mydb' }
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("SELECT * FROM dbo.Users;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
According to your comment, as your original question, you just mistaken the table name as
I have checked my database information. I found that my table name is "Table" instead of "Users", and the schema is dbo.
And now you are facing issue:
"Incorrect syntax near the keyword Table".
As the Table is a keyword in MSSQL, you can find it in https://msdn.microsoft.com/en-us/library/ms189822.aspx. In SQL sentence, we will use [] to contain the table name if the table name has a conflict with any keyword.
Try to use SELECT top 1 * FROM [Table]. Furthermore, it is better to rename the table named Table to resolve the conflicts.