I'm trying data extraction in Node.js with Firebird.
First code:
var sql1 = 'select id,id_asset_element,duration,start_datetime,show_name from MAIN_EVENT where start_datetime > DATEDIFF(millisecond, TIMESTAMP\'0001-01-01 00:00\', CURRENT_TIMESTAMP) and id_playlist=1 order by 1 asc;'
app.get('/', function(req, res) {
firebird.attach(options, function(err, db) {
if (err)
throw err;
// db = DATABASE
db.query(sql1, function(err, result) {
// IMPORTANT: close the connection
console.log(result())
db.detach();
res.render('pages/index', {
result : result
});
if(err)
console.log(err)
});
});
})
And first log:
{
ID: 744636,
ID_ASSET_ELEMENT: 86869,
DURATION: 27000,
START_DATETIME: 63760068424160,
SHOW_NAME: 'CHID, CLIP'
},
{
ID: 744637,
ID_ASSET_ELEMENT: 81723,
DURATION: 96120,
START_DATETIME: 63760068451160,
SHOW_NAME: 'CHID, CLIP'
},
This result is good.
Second Code:
var sql2 = 'select IMPORT_FIELDS from MAIN_EVENT where start_datetime > DATEDIFF(millisecond, TIMESTAMP\'0001-01-01 00:00\', CURRENT_TIMESTAMP) and id_playlist=1 order by 1 asc;'
app.get('/test/', function(req, res) {
firebird.attach(options, function(err, db) {
if (err)
throw err;
// db = DATABASE
db.query(sql2, function(err, result) {
// IMPORTANT: close the connection
console.log(result)
db.detach();
res.render('pages/test', {
result : result
});
if(err)
console.log(err)
});
});
})
And second log:
{ IMPORT_FIELDS: [Function (anonymous)] },
{ IMPORT_FIELDS: [Function (anonymous)] },
{ IMPORT_FIELDS: [Function (anonymous)] },
{ IMPORT_FIELDS: [Function (anonymous)] },
If I open, localhost:3000/test result is this:
function(callback) { // callback(err, buffer, name); statement.connection.startTransaction(ISOLATION_READ_UNCOMMITTED, function(err, transaction) { if (err) { callback(err); return; } statement.connection._pending.push('openBlob'); statement.connection.openBlob(id, transaction, function(err, blob) { var e = new Events.EventEmitter(); e.pipe = function(stream) { e.on('data', function(chunk) { stream.write(chunk); }); e.on('end', function() { stream.end(); }); }; if (err) { callback(err, name, e); return; } function read() { statement.connection.getSegment(blob, function(err, ret) { if (err) { transaction.rollback(function() { e.emit('error', err); }); return; } if (ret.buffer) { var blr = new BlrReader(ret.buffer); var data = blr.readSegment(); e.emit('data', data); } if (ret.handle !== 2) { read(); return; } statement.connection.closeBlob(blob); transaction.commit(function(err) { if (err) { e.emit('error', err); } else { e.emit('end'); } e = null; }); }); } callback(err, name, e); read(); }); }); } function(callback) { // callback(err, buffer, name); statement.connection.startTransaction(ISOLATION_READ_UNCOMMITTED, function(err, transaction) { if (err) { callback(err); return; } statement.connection._pending.push('openBlob'); statement.connection.openBlob(id, transaction, function(err, blob) { var e = new Events.EventEmitter(); e.pipe = function(stream) { e.on('data', function(chunk) { stream.write(chunk); }); e.on('end', function() { stream.end(); }); }; if (err) { callback(err, name, e); return; } function read() { statement.connection.getSegment(blob, function(err, ret) { if (err) { transaction.rollback(function() { e.emit('error', err); }); return; } if (ret.buffer) { var blr = new BlrReader(ret.buffer); var data = blr.readSegment(); e.emit('data', data); } if (ret.handle !== 2) { read(); return; } statement.connection.closeBlob(blob); transaction.commit(function(err) { if (err) { e.emit('error', err); } else { e.emit('end'); } e = null; }); }); } callback(err, name, e); read(); }); }); } function(callback) { // callback(err, buffer, name);
Problem
How can I extract [Function (anonymous)] from second log.
I'm using,
Node.js, Express, Ejs and Firebird.
Update :
npmjs.com/package/node-firebird
I found how to display blob data. This code is working for me.
select cast(BLOBDATANAME as varchar(1000) character set utf8)
Firebird-Nodejs
firebird.attach(options, function(err, db) {
if (err)
throw err;
// db = DATABASE
db.query(sql2, function(err, result) {
// IMPORTANT: close the connection
console.log(result)
db.detach();
if(err)
console.log(err)
});
});
Result:
{ CAST: '<XML></XML>' }, { CAST: '<XML></XML>' }, { CAST: '<XML></XML>' },
Thanks all, regards.
Related
I am trying to develop an APP in which I have to increase or decrease the user count according to their hobbies/interest in the master list. I am doing it in Node js with the help of loopback. Here is my code, in which I am giving two interests(i.e sketching and horse-riding):
async.forEach(data, function (interest) {
console.log("Interest is", interest);
Interest.findOne({
where:
{
'name': interest
}
}, function (err, interestObj) {
if (err) {
//return callback(err, null);
console.log("error", err);
}
else {
//return callback(null, response);
console.log("found", interestObj);
if (!interestObj) {
Interest.create({ "name": interest, "count": 1 }, function (err, response) { });
}
else {
_count = interestObj.count + 1;
interestObj.updateAttribute('count', _count, function (e, r) { });
}
}
});
// return callback(null, {});
},function(err){
console.log("success..!!")
});
}
but it is showing me only one of them in output. Here is output:
data is [ 'horse-riding', 'skeching' ]
Interest is horse-riding
Interest is skeching
found { name: 'horse-riding', count: 1, id: 59ccff0765055a212491a6bc }
found null
I think the async function is not working properly with forEach loop in this, But I am not getting where the code went wrong. I want to show all the interest given by the user, so what course of actions should I take to do it?? Thanks in advance..!!:)
It is working now...!!!
async.each(data, function (interest, callback2) {
console.log('Processing ', interest);
Interest.findOne({
where:
{
'name': interest
}
}, function (err, interestObj) {
if (err) {
console.log("error", err);
callback2(err);
}
else {
console.log("found", interestObj);
if (!interestObj) {
Interest.create({ "name": interest, "count": 1 }, function (err, response) { });
}
else {
_count = interestObj.count + 1;
interestObj.updateAttribute('count', _count, function (e, r) { });
}
callback2();
}
});
}, function (err) {
if (err) {
console.log('Failed to process', err);
} else {
console.log('All interests have been processed successfully');
}
return callback(err);
})
};
I am using MongoDB hosted with mLab and Node.js with express and TypeScript. My problem is that I can make exactly one request to the database when I run my server, and any subsequent request throws "Topology was destroyed." Here's what my code looks like.
export function getTeamName(id: string, callbackSuccess: (name) => void, callbackError?: (error) => void) {
initDb(() => {
db.collection('teams', (err: Error, teams) => {
if (err) { callbackError(err); db.close(); return; }
else {
teams.findOne({ '_id': id }, { 'name': 1 }, (error, name) => {
if (error) { callbackError(error); db.close(); return; }
else { callbackSuccess(name); db.close(); }
});
}
})
}, (err) => {
callbackError(err);
})
}
And the initDb() method:
import { Server, Db } from 'mongodb'; //using mongodb typings
var server = new Server("*******.mlab.com", *****, { auto_reconnect: false });
var db = new Db('serverName', server, { w: 1 });
function initDb(callbackSuccess: (data) => void, callbackError?: (err) => void) {
db.open((err, db) => {
if (err) {
callbackError(err);
}
else {
db.authenticate("username", "password", (error, data) => {
if (error) {
callbackError(err);
}
else {
callbackSuccess(data);
}
});
}
});
}
Thank you for your help.
Make sure your network does not have a firewall... That was my issue.
At the moment I'm running this task:
var skip = 0;
var limit = 5;
gulp.task('add coordinates to visits', function(done) {
(function recurse() {
Visit.find({})
.skip(skip)
.limit(limit)
.populate('zone')
.exec(function cb(err, visits) {
if (err) {
throw err;
}
if (visits.length === 0) {
return;
}
async.each(visits, function iterateEvents(visit, next) {
if (!visit.zone) {
return next();
} else if (!visit.coordinates.lat || !visit.coordinates.lng) {
visit.coordinates = {
lat: visit.zone.geo.coordinates.lat,
lng: visit.zone.geo.coordinates.lng
};
}
visit.save(next);
}, function cb(err) {
if (err) {
throw err;
}
skip += limit;
setTimeout(recurse, 1000);
});
});
})();
});
But I'm sure there must be a more elegant and optimal method than using skip, limit, `setTimeout. Is there some mongo or mongoose method for running updating tasks?
Based on our conversation in the comments it seems like Mongoose's querystream might be what you are looking for:
var stream = Visits.find().populate('zone').stream();
stream.on('data', function processDoc(visit) {
var self = this;
if (visit.zone && (!visit.coordinates.lat || !visit.coordinates.lng)) {
self.pause();
visit.update({
coordinates: {
lat: visit.zone.geo.coordinates.lat,
lng: visit.zone.geo.coordinates.lng
}
}, function(err, result) {
if (err) { console.log(err); };
self.resume();
});
}
});
stream.on('error', function(err) {
console.log('error', err);
});
stream.on('close', function() {
console.log('closed');
});
When I run collection.find() in MongoDB/Node/Express, I need to return value for my array like this but iam in callback hell;
foursquare.getVenues(params,function(error, venues) {
if (!error) {
var places = [];
venues.response.venues.forEach(function(e) {
places.push(
{
obj_id:e.id,
name:e.name,
distance:e.distance,
here_now:req.collection.findById(e.id) //count- i want need this value
}
);
});
res.send(places);
}
});
You can try to use Async https://github.com/caolan/async#each
var async = require('async');
...
foursquare.getVenues(params, function (error, venues) {
if (!error) {
throw err;
}
var places = [];
async.each(venues.response.venues, function (e, callback) {
db.collection.findById(e.id, function (err, res) {
places.push({
obj_id: e.id,
name: e.name,
distance: e.distance,
here_now: res
});
callback()
});
}, function (err) {
if (err) {
console.log('A file failed to process');
} else {
console.log('All files have been processed successfully');
res.send(places);
}
});
});
or Using async.map
var async = require('async');
var createArray = function (e, cb) {
db.collection.findById(e.id,function(err,res){
var obj = {
obj_id: e.id,
name: e.name,
distance: e.distance,
here_now: res
}
cb(null, obj);
});
}
async.map(venues.response.venues, createArray, function (err, places) {
if(err){
throw err;
}
console.log(places);
});
I have function
var checkTokenIsExpired = function(name, token, response) {
LoginToken.find( { name: name, series: token }, function(error, info){
console.log("info: ", info[0]['expire']);
if (error) {
// response.send("error: %s}", error);
response(error);
}
if (info.length > 0) {
var expire = new String(info[0]['expire']);
// expire = expire.substr(0,26);
var date = new Date(expire);
if (date >= new Date()) {
// response.send("{info: success" );
response("success");
}
else{
// response.send("error: token-has-expired");
response("token-has-expired");
}
console.log("Response: ", info);
}
else {
response(null);
}
} );
}
To check token is expired or not? It will return a string.
And I call this function in here
exports.updateAccount = function(newData, callback)
{
Accounts.find({name:newData.body.name}, function(err, docs){
if (err) {
callback.send('{error: ' + String(err) + "}");
}
if (docs.length==0 || !docs) {
callback.send("{error: NULL }");
}
else {
checkTokenIsExpired(newData.body.name, newData.body.token, function(error, info){
if (error){
callback.send("{error: " + error + "}");
// I want to get info here }
console.log("check token: ", info);
// check info of token is expired or not
if (info!=null && info!="token-has-expired") {
var updateString = "";
if (newData.body.screen_name){
Accounts.update( {'name': newData.body.name},
{
"screen_name" : newData.body.screen_name
},
{ 'upsert' : true },
function (err, numberAffected, raw) {
if (err) return handleError(err);
});
}
if (newData.body.email){
Accounts.update( {'name': newData.body.name},
{
"email": newData.body.email
},
{ 'upsert' : true },
function (err, numberAffected, raw) {
if (err) return handleError(err);
});
}
if (newData.body.password == ''){
} else{
var password = encodePassword(newData.body.password, docs[0]['salt']);
Accounts.update( {'name': newData.body.name},
{
"hassedPass" : password,
},
{ 'upsert' : true },
function (err, numberAffected, raw) {
if (err) return handleError(err);
});
}
}
});
}
I want to get the info when call checkTokenIsExpired but when I console.log("info", info) it return undefined.
in checkTokenIsExpired, you need to pass info to the response callback otherwise it is not in scope of your second code.
at least in the case where you have success:
response("success", info);
Instead of passing "success", you'd typically pass null to indicate there is no error.
I have solved problem
checkTokenIsExpired(newData.body.name, newData.body.token, function(error, info)
because it will take 1 parameter but I put 2
Change it into checkTokenIsExpired(newData.body.name, newData.body.token, function(info)
It will correct :D