mongodb nodejs store value outside connect - javascript

I need a way to store value outside mongoDB connect call:
read(object) {
let result
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
result = err;
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
assert.equal(err, null);
db.close();
result = docs;
});
}
});
return result
}
When i call this method, which is part of a class, return is called before result assignment, as normal.
Example: console.log(read(obj)) returns undefined
The idea is to store value in a variable and return might wait until connect terminate.
Is there any way to resolve this problem?

Without promise:
Call return inside find and err function:
read(object) {
let result
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
result = err;
return result; //here
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
assert.equal(err, null);
db.close();
result = docs;
return result; // here
});
}
});
}
Or set a timeout for return with enough time to wait for other process to end:
read(object) {
let result
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
result = err;
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
assert.equal(err, null);
db.close();
result = docs;
});
}
});
setTimeout(function(){ return result}, 3000); // 3secs
}

With Promise you can try the following:
function read(object) {
let result
return new Promise((resolve, reject) => {
MongoClient.connect(this.url, function (err, db) {
if (err!=null){
reject(err);
} else {
db.collection(object.collection).find(object.field).toArray(function(err, docs) {
db.close();
if (err) {
reject(err);
} else {
resolve(docs);
}
});
}
});
});
}
// then you can call the function and use the result like this
read(obj).then(docs => {
console.log(docs);
})
.catch(err => {
// handle error
console.log(err);
})

Related

SQlite result undefined issue in NodeJS [duplicate]

How do I get the return value from inside a value of node.js/javascript callback?
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
return "hello there is a logs";
} else {
return "there is no logs yet..."
}
})
}
var logs = get_logs();
console.log(logs);
You can't return the result from a function whose execution is asynchronous.
The simplest solution is to pass a callback :
function get_logs(cb){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
cb("hello there is a logs");
} else {
cb("there is no logs yet...)"
}
})
}
get_logs(function(logs){
console.log(logs);
});
You can't. You should instead pass another callback to your function. Something like this:
function get_logs(callback){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function(arg1) {
console.log(arg1);
});
function get_logs(callback) {
User_Log.findOne({
userId: req.user._id
}, function (err, userlogs) {
if (err) throw err;
if (userlogs) {
// logs = userlogs.logs;
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function (data) {
console.log(data);
});
Uses callbacks...
In node.js almost all the callbacks run after the function returns , so you can do something like this
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
do_something(logs)
} else {
console.log('No logs')
}
})
}

Proper way to get the result of MySQL from Node.js function callback?

What is the proper way to get the result of this MySQL Query out of GetAllFarms and into a variable called err and farms? Sorry, doing a quick code try and coming from a different language.
var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)
function GetAllFarms(callback) {
query = db.query("SELECT * FROM farms ", function (err, result) {
console.log("DEBUG:QUERY//");
console.log(query.sql);
// console.log(result)
if (err) {
// console.log(err)
return callback(err, null)
} else {
// console.log(result)
return callback(null, result)
}
});
// db.end()
console.log("query")
console.log(query.result)
return query
}
Any help is much appreciated. Thanks
You have to decide wether you want to provide result via callback or with return. Don't mix them, it's confusable.
Callback approach
var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)
function GetAllFarms(callback) {
query = db.query("SELECT * FROM farms ", function (err, result) {
console.log("DEBUG:QUERY//");
console.log(query.sql);
// console.log(result)
if (err) {
// console.log(err)
return callback(err, null)
} else {
// console.log(result)
return callback(null, result)
}
});
// db.end()
console.log("query")
console.log(query.result)
}
// usage
GetAllFarms((error, result) => {
if (error) {
// handle error
}
// process result
})
Promise approach
var err, farms = GetAllFarms()
console.log("GetAllFarms:")
console.log(farms)
console.log(err)
function GetAllFarms() {
return new Promise((resolve, rejct) => {
db.query("SELECT * FROM farms ", function (err, result) {
console.log("DEBUG:QUERY//");
console.log(query.sql);
if (err) {
return reject(err)
} else {
return resolve(result)
}
});
});
}
// usage
(async () => {
const res = await GetAllFarms();
// or
GetAllFarms().then(/* ... */).catch(/* ... */);
})

how to return array in Node.js from module

getting undefined all the time "main.js":
var dbAccess = require('../dao/dbAccess');
dbaInstance = new dbAccess();
var wordPool = dbaInstance.getWordPool();
console.log (wordPool);
and "dbAccess.js" contains:
var DatabaseAccess = function() {}
DatabaseAccess.prototype.getWordPool = function () {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
//console.log(wordPoolFromDB); -working ok
return (wordPoolFromDB);
});
}
module.exports = DatabaseAccess;
why is it not working?
DatabaseAccess.prototype.getWordPool is not returning any result.
Since you are using an asynchronous function, you need do one of these things:
a) Take a callback as parameter and invoke the callback with a result
DatabaseAccess.prototype.getWordPool = function (cb) {
RoundWord.find({}, 'words decoys', function(err, results) {
if (err) {
return cb(err, null);
}
cb(null, results);
});
}
The callback convention is: cb(error, results...)
b) Use promises
DatabaseAccess.prototype.getWordPool = function () {
return RoundWord.find({}, 'words decoys', function (err, results) {
if (err) {
throw err; // however you might want to sanitize it
}
return results;
});
}
To consume this result you will need to do it as a promise
databaseAccess.getWordPool()
.catch(function (err) {
// process the error here
})
.then(function (results) {
// something with results
});
It will work if you change to this:
var dbAccess = require('../dao/dbAccess');
dbaInstance = new dbAccess();
dbaInstance.getWordPool(function(wordPool){console.log (wordPool);});
And:
var DatabaseAccess = function() {}
DatabaseAccess.prototype.getWordPool = function (cb) {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
//console.log(wordPoolFromDB); -working ok
cb(wordPoolFromDB);
});
}
module.exports = DatabaseAccess;
If the function is Asynchronous you need to pass a callback to find to get the result:
DatabaseAccess.prototype.getWordPool = function (callback) {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
callback(err, wordPoolFromDB);
});
}
and call it as follows in main:
dbaInstance.getWordPool(function (err, wordPool) {
console.log (wordPool);
// wordPool is only available inside this scope,
//unless assigned to another external variable
});
// cannot access wordPool here

returning data from node mssql execute functions

I'm using mssql(Microsoft SQL Server client for Node.js) package from npm.I'm trying to execute a stored procedure residing in my sql server database.Everything works fine.However what I want to do is return the recordsets so that i can export this to be used in other module.Below is what I'm trying to do.
function monthlyIceCreamSalesReport (scope){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return;
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
}
else {
console.log(recordsets[0]); // successfully receiving the value
}
connObj.conn.close();
});
});
console.log('check for recordsets', recordsets[0]); // undefined
return recordsets[0];
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
As shown in the code snippet, since the value of recordsets[0] is undefined, exporting this function is of no use.
You can't return this way in async nature. You can get it by passing the callback function
Try to give a callback function like this
function monthlyIceCreamSalesReport(scope, callback) { // pass a callback to get value
var connObj = connConfig();
connObj.conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
connObj.req.input('Month', 4);
connObj.req.input('Year', 2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue) {
if (err) {
console.log(err);
} else {
console.log(recordsets[0]);
connObj.conn.close();
return callback(null, recordsets[0]); //return as a callback here and get that value in callback from where you called this function
}
});
});
}
var sqlServerObj = {
monICSalesReport: monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
Note: See the comment to understand the changes
recordsets[0] is undefinded, because is defined only in connObj.req.execute function scope. You may do this in this way:
function monthlyIceCreamSalesReport (scope, cb){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return cb(Error("Something wrong"));
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
connObj.conn.close();
return cb(Error("Something wrong"));
}
else {
console.log(recordsets[0]); // successfully receiving the value
connObj.conn.close();
return cb(recordsets[0]);
}
});
});
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;

Return from callback function in Javascript

How do I get the return value from inside a value of node.js/javascript callback?
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
return "hello there is a logs";
} else {
return "there is no logs yet..."
}
})
}
var logs = get_logs();
console.log(logs);
You can't return the result from a function whose execution is asynchronous.
The simplest solution is to pass a callback :
function get_logs(cb){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
cb("hello there is a logs");
} else {
cb("there is no logs yet...)"
}
})
}
get_logs(function(logs){
console.log(logs);
});
You can't. You should instead pass another callback to your function. Something like this:
function get_logs(callback){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function(arg1) {
console.log(arg1);
});
function get_logs(callback) {
User_Log.findOne({
userId: req.user._id
}, function (err, userlogs) {
if (err) throw err;
if (userlogs) {
// logs = userlogs.logs;
callback("hello there is a logs");
} else {
callback("there is no logs yet...");
}
})
}
get_logs(function (data) {
console.log(data);
});
Uses callbacks...
In node.js almost all the callbacks run after the function returns , so you can do something like this
function get_logs(){
User_Log.findOne({userId:req.user._id}, function(err, userlogs){
if(err) throw err;
if(userlogs){
// logs = userlogs.logs;
do_something(logs)
} else {
console.log('No logs')
}
})
}

Categories

Resources