How to use one argument repeatedly in mysql query (NODE.js) - javascript

I want to use some argument a few times in same query. How can I do this without duplication of this argument?
This works, but we have to use this argument twice
connection.query('SELECT ? FROM ?', [usr, usr],...)
I tried this, but it doesn't work (syntax error):
connection.query('SET #param = users; SELECT #param FROM #param',...)

For make it work, you have to do to things:
Enable multiple statement queries
var connection = mysql.createConnection({multipleStatements: true});
To keep your variables between queries, many times, you must use MySQL transactions.
connection.query('start transaction;set #param=?;select #param;commit',[use])
Read more:
node-mysql
Transaction in node-mysql
Transaction in MySQL

Related

How to use variable for "TOP" in the sqlQuery of cosmos DB bindings?

I was creating a simple page using durable function which is triggered by http request, getting data from cosmos db, and use the result as http response.
I used JavaScript and followed the Azure official documents.
In the Orchestrator, I called context.df.callActivity("Action1", {"top":10})
In the "Action1"'s function.json, I added a cosmos DB binding with sqlQuery as SELECT TOP {top} * FROM e.
I got error message:
The count value provided for a TOP clause must be an integer.
I've searched and tried using udf like SELECT TOP udf.toInteger({top}) *...
or built-in function like SELECT TOP StringToNumber({top}) *...
but none of them works.
So the question is how can I use a variable like "TOP x" in the sqlQuery for cosmos DB binding?

Trying to insert multiple documents/records into MongoDB via a POST request using NodeJS

I am currently building an API using MongoDB and NodeJS, and I have the following block of code to do a POST request:
// '/v1/restaurant/add' - Create
api.post('/add', (req, res) => {
let newRestaurant = new Restaurant();
newRestaurant.name = req.body.name;
newRestaurant.save(err => {
if (err) {
res.send(err);
}
res.json({ message: 'Restaurant saved successfully' });
});
});
What I would like to do is do a bulk POST (i.e. insert multiple documents/records into my MongoDB at once). How would I modify my code to accomplish this?
I apologize, but I am very new to JavaScript/NodeJS.
There are two ways to do it using Mongoose.
Model.create() - it accepts an array of objects to be inserted into the database and does as many queries to the database as the number of items to be inserted. It will be a performance hit if you want to insert lots of records, but you gain the benefit of Mongoose invoking the save() method for each of the records which means your pre and post middleware functions will get triggered. You can read more about the method here.
Model.insertMany() - it also accepts an array of objects to be inserted, but does this in a single database operation. You gain better performance but the trade of is that the save() function won't be run for any of the items you want to insert (validations will still be run before submitting the query). You can read more about insertMany() here.
Personally I would use create() if I have to insert less than 50 items at once and if my models are complicated and have pre/post-save middleware functions attached to them.
I would use insertMany() if my models aren't complicated and I have to regularly insert more than 50 items at a time.

What's remove() and save() mean in mongodb node.js when initializing one database

I am newly using node.js. I am reading the code of one app. The code below is to initialize the db, to load some question into the survey system I can't understand what's remove() and save() means here. Because I can't find any explanation about these two method. It seems mongoose isn't used after being connected. Could any one explain the usage of these methods?
Well, this is my understanding of this code, not sure to be correct. My TA tell me it should be run before server.js.
/**
* This is a utility script for dropping the questions table, and then
* re-populating it with new questions.
*/
// connect to the database
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
// load the schema for entries in the 'questions' table
var Question = require('./app/models/questions');
// here are the questions we'll load into the database. Field names don't
// quite match with the schema, but we'll be OK.
var questionlist = [
/*some question*/
];
// drop all data, and if the drop succeeds, run the insertion callback
Question.remove({}, function(err) {
// count successful inserts, and exit the process once the last insertion
// finishes (or any insertion fails)
var received = 0;
for (var i = 0; i < questionlist.length; ++i) {
var q = new Question();
/*some detail about defining q neglected*/
q.save(function(err, q) {
if (err) {
console.error(err);
process.exit();
}
received++;
if (received == questionlist.length)
process.exit();
});
}
});
To add some additional detail, mongoose is all based on using schemas and working with those to manipulate your data. In a mongodb database, you have collections, and each collection holds different kinds of data. When you're using mongoose, what's happening behind the scenes is every different Schema you work with maps to a mongodb collection. So when you're working with Question Schema in mongoose land, there's really some Question collection behind the scenes in the actual db that your working with. You might also have a Users Schema, which would act as an abstraction for some Users collection in the db, or maybe you could have a Products Schema, which again would map to some collection of products behind the scenes in the actual db.
As mentioned previously, when calling remove({}, callback) on the Questions Schema, you're telling mongoose to go find the Questions collection in the db and remove all entries, or documents as they're called in mongodb, that match a certain criteria. You specify that criteria in the object literal that is passed in as the first argument. So if the Questions Schema has some boolean field called correct and you wanted to delete all of the incorrect questions, you could say Question.remove({ correct: false }, callback). Also as mentioned previously, when passing an empty object to remove, your telling mongoose to remove ALL documents in the Schema, or collection rather. If you're not familiar with callback functions, pretty much the callback function says, "hey after you finish this async operation, go ahead and do this."
The save() function that is used here is a little different than how save() is used in the official mongodb driver, which is one reason why I don't prefer mongoose. But to explain, pretty much all save is doing here is you're creating this new question, referred to by the q variable, and when you call save() on that question object, you're telling mongoose to take that object and insert it as a new document into your Questions collection behind the scenes. So save here just means insert into the db. If you were using the official mongo driver, it would be db.getCollection('collectionName').insert({/* Object representing new document to insert */}).
And yes your TA is correct. This code will need to run before your server.js file. Whatever your server code does, I assume it's going to connect to your database.
I would encourage you to look at the mongoose API documentation. Long term though, the official mongodb driver might be your best bet.
Mongoose basically maps your MongoDB queries to JavaScript objects using schema.
remove() receives a selector, and callback function. Empty selector means, that all Questions will be affected.
After that a new Question object is created. I guess that you omitted some data being set on it. After that it's being saved back into MongoDB.
You can read more about that in the official documentation:
http://mongoosejs.com/docs/api.html#types-subdocument-js
remove query is use for removing all documents from collection and save is use for creating new document.
As per your code it seems like every time the script run it removes all the record from Question collection and then save new records for question from question list.

Getting out parameters from stored proedure

I'm using node and calling a stored procedure in MariaDB. The stored procedure has 3 out parameters. If I call perform the following query in HeidiSQL it works without problem:
CALL weekFromDate('syberdyne', '2016/01/23', #dtSOW, #siWeek, #siYear);
SELECT #dtSOW, #siWeek, #siYear;
However if I execute the exact same query in node/javascript I get an error:
MySQL, Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT #dtSOW, #siWeek, #siYear' at line 1
What is the correct way to access 'out' parameters in node/Javascript?
Solved, by modifying the connection routine in node.js and adding the parameter:
multipleStatements:true

node mssql update query, get rowcount

I'm using the NodeJS package MSSQL (https://npmjs.org/package/mssql#cfg-node-tds) to connect to a MS SQL database and perform UPDATE queries.
I understand that if an UPDATE query ends up not affecting any rows, it will still return as a success event. I would like to handle the success event differently if zero rows were affected since this is not the intended outcome of the query.
After doing some research, I found that when performing SQL queries, you can use ##ROWCOUNT to get the number of affected rows, but I've yet to figure out how to use this with the MSSQL Node package.
Has anyone used this Node package and and handled UPDATE queries the way I am trying to?
Thanks!
Okay, right from the link your provided, the node package can call stored procedures.
Either create the logic on the JS side or the TSQL side.
Since I am a DBA/Developer by trade, lets create a SP to perform the update an return the number of rows effected.
I am using the adventure works sample database.
-- use sample db
use AdventureWorks2012;
go
-- sample select
select *
from [Person].[Person]
where lastname = 'Walters';
go
-- stored procedure
create procedure usp_Update_First_Name (#id int, #first varchar(50))
as
begin
update [Person].[Person]
set [FirstName] = #first
where [BusinessEntityID] = #id;
return(##rowcount);
end
go
-- make a call
declare #ret int;
exec #ret = usp_Update_First_Name #id = 4, #first = 'Robert';
print #ret;
This call returns the following output.
(1 row(s) affected)
1
In the JS code, do action A if #ret = 0 or action B if #ret > 0.

Categories

Resources