simple function not being reconized - javascript

the below function is generating the "x" is not a function error, for the love of me I have no idea why this is happening? any help is much appreciated.
function updateShareholder() {
var date = moment().format('MM/DD/YYYY');
console.log('updateShareholder');
var data = {
companyID: agreement.applicant.applicantCompanyID,
userID: agreement.coSigner.coSignerID,
agreementID: agreement.agreement.agreementID,
stock: agreement.stock.stock
}
company_worker.updateShareholder(data, function(err, result) {
if (err) {
console.log(err);
res.send(err);
} else {
console.log('updateShareholder');
process.nextTick(function() {
emailNotification()
});
}
});
};
if it helps here is the company worker function that is called within.
module.exports.updateShareHolder = function(req, callback) {
console.log('updateShareHolder');
Company.update({
"_id": req.companyID,
"shareHolders.userId": req.userID
}, {
$push: {
"shareHolders.$.agreements": {
agreementID: req.agreementID
}
}
}, {
$set: {
"shareHolders.$.shares": ++req.shares
}
},
function(err) {
if (err) {
console.log(err);
callback(err, err);
} else {
console.log('updateShareHolder');
callback(null, 'success');
}
})
};
and this is the function that calls the so-called broken function
function moveOn() {
if (addShareHolder == 'true') {
process.nextTick(function() {
addShareholder()
});
} else if (updateShareholder == 'true') {
process.nextTick(function() {
updateTheShareholder()
});
}
};

There's a typo in the function name.
You are exporting module.exports.updateShareHolder and calling company_worker.updateShareholder. Notice the lowercase h,

Related

Res.redirect is not a function while using express in a nodejs webapp

I am trying to redirect to '/admin' route if the required data gets updated successfully but I am getting the error that res.redirect is not a function. I have tried writing return res.redirect also but it is also not working. Node experts, please help. Here I am just finding the student record on it's reg.no. basis and updating the record with its marks and redirecting to the admin page.
app.post('/admin/midterm/marks',(req,res)=>{
var m_written=[];
var m_practical=[];
var myjson=JSON.stringify(req.body);
course.subjects.map(sub=>{
if(!Array.isArray(req.body[`${sub}`]))
{
var p={subject:sub,mark:req.body[`${sub}`]}
m_written.push(p);
}
else{
var p={subject:sub,mark:req.body[`${sub}`][0]};
var q={subject:sub,mark:req.body[`${sub}`][1]};
m_written.push(p);
m_practical.push(q);
}
});
var first={
sem:course._id,
marks_sem:[{
term:ms,
m_written:m_written,
m_practical:m_practical
}]
}
if(!StudentRecord.total.length )
{
Student.updateOne({_id:check_Id},{total:first},function(err,res){
if(err)
{console.log("error");}
res.redirect('/admin');
});
}
else{
var flag=0;
StudentRecord.total.map(record=>{
if(record.sem==required_sem)
{
flag=1;
record.marks_sem.push(first.marks_sem);
Student.updateOne({_id:check_Id},{total:StudentRecord.total},function(err,res){
if(err)
{console.log("error");}
res.redirect('/admin');
});
}
});
if(flag==0)
{
StudentRecord.total.push(first);
Student.updateOne({_id:check_Id},{total:StudentRecord.total},function(err,res){
if(err)
{console.log("error");}
res.redirect('/admin');
});
}
}});
You override res in your callbacks. Name the second parameter in the callbacks result and everything will work fine.
app.post("/admin/midterm/marks", (req, res) => {
var m_written = [];
var m_practical = [];
var myjson = JSON.stringify(req.body);
course.subjects.map((sub) => {
if (!Array.isArray(req.body[`${sub}`])) {
var p = { subject: sub, mark: req.body[`${sub}`] };
m_written.push(p);
} else {
var p = { subject: sub, mark: req.body[`${sub}`][0] };
var q = { subject: sub, mark: req.body[`${sub}`][1] };
m_written.push(p);
m_practical.push(q);
}
});
var first = {
sem: course._id,
marks_sem: [
{
term: ms,
m_written: m_written,
m_practical: m_practical,
},
],
};
if (!StudentRecord.total.length) {
Student.updateOne({ _id: check_Id }, { total: first }, function (err, result) {
if (err) {
console.log("error");
}
res.redirect("/admin");
});
} else {
var flag = 0;
StudentRecord.total.map((record) => {
if (record.sem == required_sem) {
flag = 1;
record.marks_sem.push(first.marks_sem);
Student.updateOne(
{ _id: check_Id },
{ total: StudentRecord.total },
function (err, result) {
if (err) {
console.log("error");
}
res.redirect("/admin");
}
);
}
});
if (flag == 0) {
StudentRecord.total.push(first);
Student.updateOne(
{ _id: check_Id },
{ total: StudentRecord.total },
function (err, result) {
if (err) {
console.log("error");
}
res.redirect("/admin");
}
);
}
}
});

How to pass socket to setTimeout and keep it open

I'm using NodeJS and using the
tls.connect(port, host, options, callback)
To get my socket to write to. I pass it through a async.waterfall and the socket.writable property stays set to true and I can write to the socket throughout. However, if I try to use it with setTimeout, it ends up being closed. Is there a way to keep it open or is my syntax incorrect?
This is one of the calls in async waterfall:
function (sock, err, callback) {
console.log(sock.writable); // this is true
setTimeout(function(sock) {
console.log(sock.writable); // this is false but I'd like it to be true so I can use it for more logic
}, 3000, sock);
}
I've also tried
function (sock, err, callback) {
console.log(sock.writable); // this is true
var sockz = sock;
setTimeout(function() {
console.log(sockz.writable); // this is false but I'd like it to be true so I can use it for more logic
}, 3000);
}
and this
function (sock, err, callback) {
console.log(sock.writable); // this is true
setTimeout(function(sock) {
console.log(sock.writable); // this is false but I'd like it to be true so I can use it for more logic
}.bind(this, sock), 3000);
// callback(null, sock);
}], function (err, sock) {
console.log(sock.writable);
}
But all of them print false. Is my syntax incorrect or does the socket automatically close in this scenario where I'm trying to get it to wait?
Edit
Full async.waterfall:
async.waterfall([
// insert record into db
function (acb) {
dbConn.query()
.insert(tableName, ["HOST", "SERVER_NAME", "DATE_CREATED"], [hostname, "test", currentTime])
.execute(function (err, result) {
if (err) {
componentStatus.database = false;
// pass the error down to run all the functions
acb(null, sockz, componentStatus, err);
} else {
componentStatus.resultId = result.id;
acb(null, sockz, componentStatus, null);
}
});
},
// read record back
function (sockz, componentStatus, err, acb) {
if (componentStatus.resultId < 0) {
acb(null, sockz, componentStatus, err);
} else {
dbConn.query().select("ID").from(tableName).where("ID=?", [componentStatus.resultId]).execute(function (err, rows, cols) {
if (err) {
componentStatus.database = false;
acb(null, sockz, componentStatus, err);
} else {
acb(null, sockz, componentStatus, err);
}
});
}
},
// send message to rabbit
function (sockz, componentStatus, err, acb) {
sendStatusMessage(currentTime, componentStatus.resultId, function (err1, result) {
if (err1) {
componentStatus.messaging = false;
var error = err + ", " + err1;
acb(null, sockz, componentStatus, error);
} else {
console.log("rabbit timeout");
console.log(sockz.writable);
setTimeout(function(sockz) {
console.log("In timeout");
console.log(sockz.writable);
}.bind(this, sockz), 3000); // wait for 3s to check record was consumed
}
});
}
], function (err, sockz, componentStatus, actualError) {
console.log(sockz.writable);
});
}
});
};
exports.sendStatusMessage = function(dateCreated, id, callback) {
var notification = { "dateCreated": dateCreated, "id": id };
_sendMsg("test.queue", notification, {"contentType": "application/json"}, function (err, result) {
if (err) {
callback(err, null);
} else {
callback(null, result);
}
});
}

Node js Query Async Map function is call

function(dataValue, cb) {
req.app.db.models.User.find({
_id: { $ne: dataValue._id }
}, function(err, totalUser) {
if (!err) {
var len = totalUser.length;
if (len !== 0) {
req.app.utility.async.map(totalUser, function(each, callback) {
console.log(each);
req.app.utility.async.mapSeries(each.nonregisterContact, function(element, callback1) {
console.log('element', element.number);
console.log('dataValue', dataValue.mobileNumber);
console.log('kolka', Number(element.number) === Number(dataValue.mobileNumber));
if (Number(element.number) === Number(dataValue.mobileNumber)) {
each.registerContact.push(dataValue._id.toString());
each.nonregisterContact.splice(element, 1);
each.save(function(err, finalResult) {
if (!err) {
} else {
console.log(err);
}
})
callback1(null, null);
} else {
callback1(null, null);
}
}, function(err, final) {
if (!err) {
callback(null, null);
} else {
console.log(err);
}
});
}, function(err, result) {
if (!err) {
console.log('2');
return cb(null, dataValue);
} else {
console.log(err);
}
});
} else {
return cb(null, dataValue);
}
} else {
cb(err);
}
})
}
I don't get any response after each.save method call in the mapSeries method final callback.I am trying this solution.How i will do the same thing. How I resolve that and handle this kind of situation?
I tried to simplify code, but I'm not sure that my code realizes your needs. Also I cann't test it :D
dataValue, each, element, finalResult are very common names, so you should use them with caution to keep code is readable/supportable.
// very bad idea is include other libraries to app
var async = require('async');
var db = require('db'); // this module must export connection to db
...
function (dataValue, cb) {
// processUser use data from closure of current function => inside of current
function processUser (user, callback) {
async.mapSeries(user.nonregisterContact, function(contact, callback){
// Check and exit if condition is not satisfied. It's more readable.
if (Number(contact.number) !== Number(dataValue.mobileNumber))
return callback(null); // ignore user
user.registerContact.push(dataValue._id.toString());
user.nonregisterContact.splice(contact, 1);
user.save(function(err, finalResult) { // Is finalResult ignore?
if (err)
console.log(err);
callback(); // ingnore error
})
}, callback);
db.models.User.find({_id: { $ne: dataValue._id }}, function(err, userList) {
if (!err)
return cb(err);
if (userList.length == 0)
return cb(new Error('Users not found'));
// use named function to avoid stairs of {}
async.map(userList, processUser, cb);
})
};

Callback/Promises implementation for a boolean check

Currently I have the following callback system:
var saveTask = function(err, result) {
if (err) return callback(err, result);
var newid = mongoose.Types.ObjectId();
var task = new Task({
_id: newid,
taskname: req.body.name,
teamid: req.body.team,
content: req.body.content,
creator: req.user.userId
});
task.save(function (err) {
if (!err) {
log.info("New task created with id: %s", task._id);
return callback(null, task);
} else {
if(err.name === 'ValidationError') {
return callback('400', 'Validation error');
} else {
return callback('500', 'Server error');
}
log.error('Internal error(%d): %s', res.statusCode, err.message);
}
});
};
if (req.body.team) {
valTeam.isMember(req.body.team, req.user._id, function (err, done) {
if (err) {
saveTask('403', 'Not the owner or member of this team');
} else {
saveTask(null, true);
}
});
} else {
saveTask(null, true);
}
valTeam.isMember
exports.isMember = function(teamid, userid, callback) {
Team.find({'_id':teamid, $or:[{'creator': userid }, {'userlist': { $in : [userid]}}]}, function(err, result) {
if (err) return err;
console.log(result);
if (!result.length)
return callback('404', false);
else
return callback(null, true);
});
}
In short, if team is sent by POST, I'm checking if the user is member of that ID in valTeam.isMember. Am I using the correct syntax and best method to call back my saveTask function to save the task if the user is part of the team?
This code currently works, but I feel like there should be an easier way to do it? How could I use a promise to achieve the same thing?
Thanks in advance.
It's curious the fact that you create objects instead Schemas. However "every head is a different world", this is my way:
task.save(function(error, data){
if (error) {
trow error;
} else {
//Make whatever you want here with data
});

Node.js multiple query transactions

I'm using the following function for handling multiple query transactions:
db.js
function waterfall (tasks, callback) {
pg.connect(conString, function (err, client, done) {
if (err) {
return callback(err);
}
//client.query(begin_transaction, function (err) {
client.query('BEGIN', function (err) {
if (err) {
done();
return callback(err);
}
var wrapIterator = function (iterator) {
return function (err) {
if (err) {
//client.query(rollback_transaction, function () {
client.query('ROLLBACK', function () {
done();
callback(err);
});
}
else {
var args = Array.prototype.slice.call(arguments, 1);
var next = iterator.next();
if (next) {
args.unshift(client);
args.push(wrapIterator(next));
}
else {
args.unshift(client);
args.push(function (err, results) {
var args = Array.prototype.slice.call(arguments, 0);
if (err) {
//client.query(rollback_transaction, function () {
client.query('ROLLBACK', function () {
done();
callback(err);
});
}
else {
//client.query(commit_transaction, function () {
client.query('COMMIT', function () {
done();
callback.apply(null, args);
})
}
})
}
async.setImmediate(function () {
iterator.apply(null, args);
});
}
};
};
wrapIterator(async.iterator(tasks))();
});
});
}
(referred from http://baudehlo.com/2014/04/28/node-js-multiple-query-transactions/)
What's wrong with the following function:
plot.js
db.waterfall([
function(client,cb){
client.query("INSERT INTO mydb.plotsold" +
"(plot_id, agent_id, plot_price, plot_date) VALUES " +
"($1,$2,$3,$4) RETURNING id", soldInfo.PlotId, soldInfo.agentId,
soldInfo.soldPrice, soldInfo.newDate,cb);
},
function(client,results,cb){
client.query("update mydb.listing " +
"set status =2 where id = $1 RETURNING id",soldInfo.listingId,cb);
}
],cb);

Categories