nodejs mssql return recordset - javascript

Im trying to past the recordset from mssql request.query like a return value.
Following the code on https://www.npmjs.com/package/mssql is easy to make a a console output but when I try to asign the recordset to another variable doesnt work. What Im doing wrong?
var sql = require('mssql');
var config = {
user: 'sa',
password: 'XXXXXX',
server: '192.168.8.25',
database: '3TWIMDB',
}
var resultado='';
sql.connect(config, function(err){
var request = new sql.Request();
request.query('select 1 as VehiCLASS',function(err,recordset){
console.log(recordset[0].VehiCLASS);
resultado = recordset[0].VehiCLASS;
});
sql.close();
});
console.log("rsul: "+resultado);
Thanks.

The query is run asynchronously. console.log actually runs before resultado = recordset[0].VehiCLASS completes, so it's not set.
You must synchronize any code that relies on asynchronous operations. You have to do this by using the callbacks:
resultado = recordset[0].VehiCLASS;
console.log("rsul: ", resultado);
You may also specify your own callback function to prevent nesting:
function queryComplete(err, result) {
// should handle error
console.log("rsul: ", result);
}
resultado = recordset[0].VehiCLASS;
queryComplete(null, resultado);

Related

(Javascript Node.js) How to get varibles from a IIFE

Please see my code below:
I am trying to assign the recordset to a variable, can use index.js to call this variable out.
I am able to console.log the recordset. But when I call this IIFE, it is always says undefined.
var mssql = require('mssql');
var dbcon = require('./dbcon');
var storage = (function () {
var connection = new mssql.Connection(dbcon);
var request = new mssql.Request(connection);
connection.connect(function (recordset) {
request.query('select getdate()', function (err, recordset) {
console.dir(recordset);
});
connection.close();
});
})();
module.exports = storage;
index.js
var storage = require('./storage');
"AMAZON.HelpIntent": function (intent, session, response) {
storage(function (recordset){
var speechOutput = 'Your result is '+recordset;
response.ask(speechOutput);
});
However, I can't get the recordset. I got "Your result is {object, object}. "
that's because the IIFE is executing right away, try returning a function instead and then executing that function when you import that module,
var storage = (function(mssql, dbcon) {
return function() {
var connection = new mssql.Connection(dbcon);
var request = new mssql.Request(connection);
connection.connect(function(recordset) {
request.query('select getdate()', function(err, recordset) {
console.dir(recordset);
});
connection.close();
});
}
})(mssql, dbcon);
and I don't understand why you need the IIFE, why don't you just assign the function to the variable?
If you're trying to assign the variable "recordset" to "storage" then this will never work as "connection.connect" is an asynchronous function, and in that case you should think about callback functions or promises.
Update
Based on your request, here's an implementation with a callback function and how it's used
var mssql = require('mssql');
var dbcon = require('./dbcon');
var storage = function(callback) {
var connection = new mssql.Connection(dbcon);
var request = new mssql.Request(connection);
connection.connect(function(recordset) {
request.query('select getdate()', function(err, recordset) {
if(!err && callback){
callback(recordset);
}
connection.close();
});
});
}
module.exports = storage;
// --------------------------------------------------
// implementation in another module
var storage = require("module_path"); // (1)
var answer;
storage(function(recordset){ // (2)
answer = recordset;
console.log(answer); // actual data, (3)
// implement your logic here
});
console.log(answer); // undefined (4)
// --------------------------------------------------
How this code works:
- You start by calling the storage method and sending it a callback method.
- The whole point of the callback function is that you won't wait for the result, your code will actually continue working at the same time that the storage method is connecting to the database and trying to get the data, ans since db operations are much slower, line(4) will execute before line(3).
- The flow of work will be as follows:
line (1)
line (2)
line (4)
line (3) at sometime in the future when the data is retrieved from database
- To see this more clearly, try doing this at the last line,
setTimeout(function(){console.log(answer);}, 3000);
This will wait for sometime until the data comes back;

Returning queries from couchdb using nano

i've written a simple module to handle my couchdb CRUD operations using nano, however i'm having hardship returning from the results i query from the couch database. My Code is as follows.
couchdb.js
//Select from couch view
exports.couchSelect=function (_db, document,view) {
return _db.view(document, view,function(err, body){
if(!err){
var rows = body.rows; //the rows returned
console.log(rows);
return rows;
}else{
console.log(err);
}
}
);
}
routes.js
var couchdb = require('./couchdb');
app.get("/orders", function (req, res) {
var db = couchdb.couchConnect('ezyextension_orders');
var insert = couchdb.couchSelect(db, 'orders', 'orders');
console.log(insert);
});
On executing the returned output is only get Node http request parameters without the returned rows, need help to return the actual JSON rows queried.Thanx
You're using nano which use callback to make async calls. Returning _db.view only return a void function. I added comments to tell you what is happening :
exports.couchSelect = function(_db, document, view) {
_db.view(document, view, function(err, body) {
//This will be called after the couchSelect request.
if (!err)
console.log("Callback : " + body.rows);
});
}
//When you use it
var couchdb = require('./couchdb');
app.get("/orders", function(req, res) {
var db = couchdb.couchConnect('ezyextension_orders');
var insert = couchdb.couchSelect(db, 'orders', 'orders');
//This is synchronous. This will be called before the callback is called.
console.log(insert);
});
I decided to use blue-nano which uses promises instead of callbacks and the code is as below.
couchdb.js
var nano = require('nano-blue')('http://localhost:5984');
//Select from couch view
exports.couchSelect=function (_db, document,view) {
return _db.view(document, view);
}
routes.js
app.get("/orders", function (req, res) {
var db = couchdb.couchConnect('ezyextension_orders');
couchdb.couchSelect(db, 'orders', 'all').spread(function (body,header) {
res.send(body.rows);
}).catch(function(err) {
console.log(err.message);
});
});
This works perfectly

get count collection with socket.io-mongodb

I'm trying to make a simple task.
In the first place, on client side, i'm sending data to server and then i insert these data into my mongodb database.
Then i try to get count of clients from my database.
var express = require('express');
var MONGO_URL = "mongodb://localhost:27017/mydatabase";
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongo = require('mongodb').MongoClient,
fs = require('fs');
var countUserSuscribed =0;
//here i insert data
/* Connection events */
io.on('connection', function (client) {
console.log("User connected");
client.on('InsertNewUser', function (newUser) {
console.log("we ar in InsertNewUser event");
//////////////////////////////////////////////////////////
mongo.connect(MONGO_URL, function (err, db) {
console.log("we are connected to mongodb");
var Users = db.collection('User');
console.log("on crée la collection et on fait l'ajout");
Users.insert({ player: myP }, function (err, o) {
if (err) { console.warn(err.message); }
else { console.log("user inserted into db: user"); }
});
});
})
});
//GET COUNT USER
console.log("here we get count user");
mongo.connect(MONGO_URL, function (err, db) {
countUserSuscribed = Users.count();
console.log("we got " + countUserSuscribed + " user in mongoDB");
});
With this code i can create collections and insert documents but the count function doesn't work and i didn't find much explanations on npm documentation.
Is it possible to use others mongodb functions than insert and collection with socket.io-mongodb ?
If it is, can someone give an example or explain me how to use it?
The count function works but is async function and takes a callback.
here's the fix:
countUserSuscribed = Users.count(function (err,c) { console.log(c) });
https://www.npmjs.com/package/mongodb-autoincrement consider using that. It keeps a track of all inserted document. Plus it has a handy feature to get the next count. Example let's say you inserted two records. If you call next count it will show 3. There fore to get the total documents inserted call get next count - 1. Make sense?
Sorry here is the correct one. https://www.npmjs.com/package/mongoose-auto-increment

Error with java script while retrieving documents from mongodb

Basically the idea is to get documents by calling a function from MongoDB using JavaScript (not Node.js)
var mongo = require('mongodb');
mongo.MongoClient.connect('mongodb://localhost:27017/Database',function(err,db)
{
var result = [];
result = db.eval('getContacts("_id")',function(error, result)
{
console.log("Error is:" +error);
console.log("result is:"+result);
console.log("working till here");
})
// db.close();
});
note: getConatcts is a DB function to get contact related details.
Error: Error is:null
result is:
working till here

Nodejs callback with bad workflow

I'm new with NODE and I'm trying this code:
require('../../constants.js');
function dbConnect() {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : DB_HOST,
database : DB_NAME,
user : DB_USER,
password : DB_PASS,
});
connection.connect(function(err) {
console.log("Database is connected ...");
});
return connection;
}
function dbDisconnect(connection) {
connection.end();
console.log("Closing DB Connection");
}
function findPlayer(surname) {
var connection = dbConnect();
console.log("Finding -> " + surname);
var query = 'SELECT * FROM players WHERE surname = "' + surname + '"';
connection.query(query, function(err, rows, fields)
{
if (err) throw err;
for (var i in rows) {
console.log('Players: ', rows[i].surname);
}
});
dbDisconnect(connection);
}
exports.findPlayer = findPlayer;
After that, I've a laucher file:
require('./constants.js');
var aar = require('./libs/DBManager.js')
console.log('Loading DBManager');
var player = aar.findPlayer('Potter');
console.log(player);
Correct workflow is:
Loading DBManager
Database is connected...
Finding -> Potter
Players: Potter
Closing DB Connection
However the result is:
Loading DBManager
Finding -> Potter
Closing DB Connection
undefined
Database is connected...
Players: Potter
What's my wrong? Is some callback issue?
You are closing your connection before your query is for sure done.
you should put the dbDisconnect(connection); after the end of the query but inside the callback.
connection.query(query, function(err, rows, fields)
{
if (err) throw err;
for (var i in rows) {
console.log('Players: ', rows[i].surname);
}
dbDisconnect(connection);
});
also the findPlayer is not returning anything, so the console.log(player); will be undefined
Javascript is Async in nature, it doesn't wait for I/O operations. Any network call including request to connect to a DB comes under I/O operations.
The problem is that you are requesting a DB connection and before it is returned, you are making call to get data for players. I suggest you pass a callback method to the
dbConnect(callback)
And in that callback, you pass the query or operation you want to execute:
Create a callback method that contains the code to retrieve the players information
Call dbConnect() to establish the connection to DB and pass the callback as an argument
After connection is established, execute the callback
After you are done, you can close the connection, but make sure the code to close the connection, is with in the callback and is executed only after you received the data from Db
On the contrary if you are comfortable with ORM, i suggest you try Sequelize, it abstracts out the requirement to create and disconnect connections with DB, so you can focus on your crud operations.

Categories