Connection to Mongodb through Node.js - javascript

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);

Related

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

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');
});
});

Getting result from MySQL

My backend is consist of Api and DB. When I want to get response from DB I have had delayed output by 1 query.
API (I think api is ok. Start read DB first)
app.post('/api/query', (req, res) => {
console.log(`\n Query input : ${JSON.stringify(req.body)}`);
let queryInput = (Object.values(req.body).join(' '));
if(!dbApi.checkArray(queryInput)){ //If array is not made from clear strings
res.json(dbApi.queryFromUser(queryInput));
}
else{
res.json(dbApi.queryOutput);
}
});
app.listen(dbConfig.server.port, () =>
console.log(`Server running on port ${dbConfig.server.port}`));
DB
queryOutput = [];
const receivingQuery =(queryInput) => {
db.query(queryInput, (err, result) =>{
if(err) throw err+' : '+queryInput;
queryOutput = result;
console.log("\nQuery output "+ JSON.stringify(queryOutput)); //Output (result) is ok
});
return queryOutput //Here is Output from previous query (sends to API)
}
module.exports = {
queryOutput: queryOutput,
queryFromUser: receivingQuery,
}
I tryied callback method and I rewrite it couple of times. But I dont have enough skill to solve it.
If You want to return result of query so simply do following things:
add query method to db module:
function query(sql, args = []) {
return new Promise(function(resolve, reject) {
db.query(sql, args, (err, result) => {
if (err) return reject(err);
resolve(result);
});
});
}
// extra feature, getting user by id
async function getUserById(id) {
const result = await query('SELECT * FROM users WHER id = ? LIMIT 1', [id]);
if (Array.isArray(result) && result[0]) return result[0];
return null;
}
module.exports = {
query,
getUserById, // export user by id
queryOutput,
queryFromUser: receivingQuery,
}
use it (with async and await):
app.post('/api/query', async (req, res) => {
try {
console.log('Query input:', req.body);
const queryInput = Object.values(req.body).join(' ');
const result = await dbApi.query(queryInput);
res.json(result);
}
catch (error) {
console.error(error);
res.status(500).json({message: 'Please try again soon'});
}
});
app.get('/api/users/:id', async (req, res) => {
try {
const user = await dbApi.getUserById(req.params.id);
if (!user) return res.status(404).json({message: 'User not found'});
res.status(200).json(user);
}
catch (error) {
console.error(error);
res.status(500).json({message: 'Please try again soon'});
}
});
app.listen(dbConfig.server.port, () =>
console.log('Server running on port', dbConfig.server.port));

Passing a variable from ReactJS frontend to NodeJS back end using a GET route

I am working on a react app and am trying to find a way to pass a variable I define in my front-end (Question.js) to my back-end (server.js) so that I can issue different queries. I have the code
//Question.js
state = {
data: null
};
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
//server.js
con.connect(function (err) {
if (err) throw err;
con.query("SELECT question FROM s1questions WHERE ID = 1", function (err, result, fields) {
if (err) throw err;
app.get('/express_backend', (req, res) => {
var x = JSON.stringify(result[0].question);
res.send({ express: `${x}` });
});
});
});
Your sever should probably split your database connection from your route handler definitions. Also, you could use query parameters to access questions based on their id in the database.
// question.js
callBackendAPI = async () => {
const response = await fetch(`/express_backend?questionId=1`);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
// server.js
app.get('/express_backend', (req, res) => {
const { questionId } = req.query;
// query database for question by id
});

I want to take out the result from mysql's connection.query and save it in global scope chain in nodejs

I tried bringing out result by storing in variable current product. But I cant use it outside the function, so my array returns empty
var connection = mysql.createConnection({
host: config.config.mysql.opencart_local.host,
user: config.config.mysql.opencart_local.user,
password: config.config.mysql.opencart_local.password,
database: config.config.mysql.opencart_local.database
})
var query_current_products = 'select * from table;';
var current_products = [];
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
connection.query(query_current_products, function (err, result) {
if (err) throw err;
//console.log(result);
current_products = result;
});
}
)
console.log(current_products);
enter image description here
Try to use async/await syntax to get your results
const mysql = require('mysql'); // or use import if you use TS
const util = require('util');
const conn = mysql.createConnection({
host: config.config.mysql.opencart_local.host,
user: config.config.mysql.opencart_local.user,
password: config.config.mysql.opencart_local.password,
database: config.config.mysql.opencart_local.database
});
var current_products = [];
//
var query_current_products = 'select * from table;';
(async function getProducts () => {
try {
const rows = await query( query_current_products);
console.log(rows);
current_products=rows;
} finally {
conn.end();
}
})()
use this code:
var query_current_products = 'select * from users';
var current_products = [];
function f() {
return new Promise(resolve => {
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
con.query(query_current_products, function (err, result) {
if (err) throw err
resolve(result);
});
});
})
}
async function asyncCall() {
current_products = await f();
console.log("outside callback : ", current_products);
}
asyncCall();

express.js and soap calls

I am using express.js, node.js and node-soap.js and I am getting an error I can not fix.
I have the following code which fails with an exception and I can not see anything in the exception.
var soap = require('soap');
var url = 'http://www.webservicex.net/stockquote.asmx?WSDL';
var args = {
symbol : 'AMZN'
};
soap.createClient(url, function(err, client) {
client.GetQuote(args, function(err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
});
});
and in the console all I see is:
{ GetQuoteResult: [ 'exception' ] }
Thoughts?
Reza
this is the code that finally got working...
var args1 = {"tns:symbol": "AMZN"};
var url1 = "http://www.webservicex.net/stockquote.asmx?WSDL";
soap.createClient(url1, function(err, client) {
console.log(client.describe().StockQuote.StockQuoteSoap.GetQuote);
client.StockQuote.StockQuoteSoap.GetQuote(args1, function(err, result) {
if (err) {
console.error(err);
return;
}
console.log(result);
});
});

Categories

Resources