How to resold syntax error in insert sql query (Node js) - javascript

I am trying to Insert data into the MSSQL database, but there is a syntax error
Code
app.get('/PostItem', (req, res) => {
let post = ['test', 'tesa', 1];
let sql = 'INSERT INTO [dbo].[Item](ItemCode,ItemName,CreatedBy) VALUES (?,?,?)';
let query = con.query(sql, post, err => {
if (err) {
throw err
}
res.send('Item added');
})
});
error
this the error
(node:8584) UnhandledPromiseRejectionWarning: RequestError: Incorrect syntax near '?'.
NOTE: "database connection is work"

SQL Server doesn't use ? then I change code like this and it works.
app.get('/PostItem', (req, res) => {
var post = ["'test'", "'test'", 1];
var sql = `INSERT INTO [dbo].[Item](ItemCode,ItemName,CreatedBy) VALUES (${post})`;
var query = con.query(sql, err => {
if (err) {
throw err
}
res.send('Item added');
});
});

Related

Connection to Mongodb through Node.js

Hii Everyone
In my code, There is an API that works fine.
And I'm trying to connect to MongoDB from Node for the sake of inserting the data from the API.
As you can see, I get this error -
"message": "Uncaught SyntaxError: Unexpected identifier",
it looks like there is a problem with MongoClient.
I looked at the answers on this site about those topics and no one solves my problem.
Thanks for any help!
let http = require('http');
let weatherKey = process.env.weatherKey;
// console.log(weatherKey);
function getData(cb) {
http.get(`http://api.openweathermap.org/data/2.5/weather?q=israel&appid=${weatherKey}`, res => {
let data = ""
res.on('data', string => {
data += string
})
res.on('end', () => {
let obj = JSON.parse(data)
cb(obj);
})
}).on("error", error => {
cb(error);
})
}
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
function connectToMongo(data)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("weather-db");
dbo.collection("node").insertOne(data, err => {
if (err) throw err;
console.log("documents inserted");
db.close();
});
});
getData(connectToMongo);
Your function is missing { after (data)
You were missing {} in your code.
let http = require('http');
let weatherKey = process.env.weatherKey;
function getData(cb) {
http.get(`http://api.openweathermap.org/data/2.5/weather?q=israel&appid=${weatherKey}`, res => {
let data = ""
res.on('data', string => {
data += string
})
res.on('end', () => {
let obj = JSON.parse(data)
cb(obj);
})
}).on("error", error => {
cb(error);
})
}
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
function connectToMongo(data){
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("weather-db");
dbo.collection("node").insertOne(data, err => {
if (err) throw err;
console.log("documents inserted");
db.close();
});
});
}
getData(connectToMongo);

nodejs api insert into db but sends response 0

Whenever I hit this api with sending this
[{"project_id": "knsfviv9",
"coach_id": ""
},
{"project_id": "ovsijiov9",
"coach_id": ""
}]
it inserts into database but it gives response 0 as the result variable remains 0. result variable gets incremented but in res.send it sends 0.
can someone help me with this?
app.post('/api/patc/:id', (req, res) => {
let projectList = req.body;
projectList.forEach(element => {
let data = {
patc_id: "patc-" + randomID(),
college_id: req.params.id,
project_id: element.project_id,
coach_id: element.coach_id,
date: NOW()
};
let sql = "INSERT INTO projects_assigned_to_colleges SET ?";
conn.query(sql, data, (err, results) => {
if (err) throw err;
result.push(results);
});
});
res.send(JSON.stringify({ "status": 200, "error": null, "response": result }));
});
You are trying to execute asynchronous code in forEach which is giving you undesired behavior. Change the code to something like this
app.post("/api/patc/:id", async (req, res) => {
let projectList = req.body;
var result = 0;
const result = await Promise.all(projectList.map(element => {
let data = {
patc_id: "patc-" + randomID(),
college_id: req.params.id,
project_id: element.project_id,
coach_id: element.coach_id,
date: NOW()
};
return new Promise((resolve, reject) => {
let sql = "INSERT INTO projects_assigned_to_colleges SET ?";
conn.query(sql, data, (err, results) => {
if (err) throw err;
resolve(results);
});
});
}));
res.send(JSON.stringify({ status: 200, error: null, response: result }));
});

Make query for every object in json using for or forEach

My problem is, I want to make INSERT query for every object from JSON using some loop, but I almost always got an error "Cannot set headers after they are sent to the client".Can someone help?Tnx
const connection = require('./config');
module.exports.excel = function (req, res) {
var _query = 'INSERT INTO excel (id, first_name, last_name) values ?';
var jsonData = req.body;
var values = [];
function database() {
return new Promise((resolve, reject) => {
jsonData.forEach((value) => {
values.push([value.id, value.first_name, value.last_name]);
connection.query(_query, [values], (error, results) => {
if (error) {
reject(
res.json({
status: false,
message: error.message
}))
} else {
resolve(
res.json({
status: true,
data: results,
message: 'Excel file successfully created in database'
}))
}
});
});
})
}
async function write() {
await database();
}
write();
}
After I got JSON from my Angular 6 front I put req.body into jsonData and try with forEach to put every object("value" in this case) into query and write that into Excel file.
You will have to wrap each query in a Promise and wait for all to complete before sending the response using Promise.all
Not that database() is going to throw when one of the queries fail and you won't have any access to the resolved promises.
const connection = require('./config');
module.exports.excel = function(req, res) {
const _query = 'INSERT INTO excel (id, first_name, last_name) values ?';
const jsonData = req.body;
function database() {
return Promise.all(
jsonData.map(
value =>
new Promise((resolve, reject) => {
const values = [value.id, value.first_name, value.last_name]
connection.query(_query, [values], (error, results) => {
if (error) {
reject(error.message);
return;
}
resolve(results);
});
})
)
);
}
async function write() {
try {
const results = await database();
res.json({
status: true,
data: results,
message: 'Excel file successfully created in database'
});
} catch (e) {
res.json({
status: false,
message: e.message
});
}
}
write();
};

Fetch data from api(RESTful) db(mongodb) according to user input

I have created an api using nodejs, express and mongodb. I am fetching data now without sending any query. But in my frontend I have an input where the user can search for a recipe. So for example if a user types "Today" i should get response related to today only. How to check that in db and retrieve data?
module.exports = function(app, db) {
app.get("/dates/", (req, res) => {
db
.collection("dates")
.find()
.toArray((err, item) => {
if (err) {
res.send({ error: "An error has occured" });
} else {
res.send(item);
}
});
});
While making the api call , pass the dish as query parameter
For example '/recipes/?dish="Pizza" '
and in the express use the following.
module.exports = function(app, db) {
app.get("/recipes/", (req, res) => {
let queryDish = req.query.dish; // assuming /recipes/?dish="Pizza"
let query = { 'title' : { '$regex' : queryDish, '$options' : 'i' } };
db
.collection("recipes")
.find(query)
.toArray((err, item) => {
if (err) {
res.send({ error: "An error has occured" });
} else {
res.send(item);
}
});
});

What cause "Error: Uncaught (in promise): Response with status:200 for Url:null" to show up?

I'm accessing a Mongo database through NodeJS and Express as below:
var MongoClient = require('mongodb').MongoClient;
...
app.get("/app/visits", function (req, res, next) {
console.log("get visits");
MongoClient.connect('mongodb://localhost:27017/db', function (err, db) {
if (!err) { console.log("We are connected"); }
visits = db.collection('visits', function (err, collection) { });
visits.find().toArray(function (err, user) {
this.user = JSON.stringify(user);
if (err) { throw err; } else console.dir(this.user);
});
res.send(this.user);
});
});
In the browser this works fine. If I change res.send(this.user); to res.status(301).send(this.user); the status is also changed.
But the problem, Angular 2 with native script code returns the error:
getActualVisits()
{
return this.http.get("http://localhost:1234/app/visits").map(response => response.json())
}
I have no idea WHY after 7 hours of trying repair that.
Method getActualVisits() is calling from:
getActualSpecialization() {
let v = this.getActualVisits();
...
}
You need to call .subscribe after .map in order to observe the values that are returned.
getActualVisits() {
return this.http.get("http://localhost:1234/app/visits")
.map(response => response.json())
.subscribe(
data => this.actualVisits = data,
err => this.logError(err),
() => console.log('get actual visits complete')
);
}
See the following docs for more information https://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/

Categories

Resources