Mongoose findOne inside async.each - asynchronous

I want to loop through a array and check if the object exists in mongodb and then insert or update.
For which I am using async.each and then call Model.findOne inside it. But the findOne is never getting executed.
exports.ProcessNasVirtualDevices = function ProcessNasVirtualDevicesInfo (virtualDevices, callback)
{
console.log("Started Virtual Devices");
var virtualDeviceIds = [];
if (virtualDevices != null) {
//Loop through the virtual devices
async.each(virtualDevices, function (objVirtualDevice, cb) {
NasVirtualDevice.findOne({ VirtualDeviceName: nasVirtualDeviceName, PhysicalDeviceName: nasPhysicalDeviceName }, function (err, virtualDevices) {
if (err) {
cb("", err);
}
else {
console.log("Found Virtual Device");
if (virtualDevices) {
console.log(nasVirtualDeviceName + " found");
for (virtualDeviceProps in objVirtualDevice) {
console.log("Properties - " + virtualDeviceProps);
virtualDevices[virtualDeviceProps] = objVirtualDevice[virtualDeviceProps];
}
virtualDevices.save(function (err) {
if (err) {
cb("", err);
}
console.log("NasVirtualDevice " + objVirtualDevice.VirtualDeviceName + " updated");
cb();
});
}
else {
var nasVirtualDevice = new NasVirtualDevice();
for (virtualDeviceProps in objVirtualDevice) {
console.log("Properties - " + virtualDeviceProps);
nasVirtualDevice[virtualDeviceProps] = objVirtualDevice[virtualDeviceProps];
}
nasVirtualDevice.save(function (err) {
if (err) {
cb("", err);
}
console.log("NasVirtualDevice " + objVirtualDevice.VirtualDeviceName + " added");
cb();
});
}
}
});
}, function (err) {
// if any of the file processing produced an error, err would equal that error
if (err) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('A Nas Virtual Device Failed');
} else {
console.log('All Virtual Device completed successfully');
}
});
callback("Nas Virtual Devices Completed");
}
}

Related

Meteor.call and server methods not working properly

I have this code on my meteor app:
// client side
Template.lead.events({
'submit .insertExternalAccountForm': function (event) {
event.preventDefault();
Session.set('mcsStatus', 'Creating external account ...');
var target = {
code: event.target.code.value,
leadId: event.target.leadId.value,
name: event.target.name.value,
username: event.target.username.value,
password: event.target.password.value,
searchSourceId: event.target.searchSourceId.value,
clientId: event.target.clientId.value,
clientUserId: event.target.clientUserId.value
};
var noFormError = true;
if (target.username.length === 0) {
Session.set("username_error", "Field must not be empty");
noFormError = false;
} else {
Session.set("username_error", null);
}
if (target.password.length === 0) {
Session.set("password_error", "password must not be empty");
noFormError = false;
} else {
Session.set("password_error", null);
}
if (!noFormError) {
return noFormError;
}
Meteor.call('createExternalAccount', target, function (err, res) {
if (err) {
console.error(err);
}
console.log('in meteor call');
Router.go('/' + res.domain + '/' + res.externalId);
});
}
});
//server side
var createExternalAccountSync = function (query, external) {
return models.SearchSources.findOne(query).exec()
.then(function (searchsource) {
external.domain = searchsource.source;
var emr = searchsource.source.split('-');
return models.Organization.findOne({externalId: emr[2]}).exec();
}).then(function (org) {
console.log('after org');
external.organizationId = org._id;
return models.AppUser.findOne({clientId: external.clientId, externalId: external.clientUserId }).exec();
}).then(function (user) {
console.log('after app user');
external.userId = user._id;
external.userIds = [user._id];
return new Promise(function (resolve,reject) {
console.log('saveOrUpdate');
models.ExternalAccount.saveOrUpdate(external, function (err, newE) {
if (err) {
console.error(err)
reject(err);
}
resolve(newE)
});
});
})
.catch(function (e) {
console.error(e);
throw new Meteor.Error(e);
});
};
Meteor.methods({'createExternalAccount': function (data) {
var query = {};
var newExternalAccount = new models.ExternalAccount();
newExternalAccount.username = data.username;
newExternalAccount.password = data.password;
newExternalAccount.externalId = data.username;
newExternalAccount.name = data.name;
newExternalAccount.clientId = data.clientId;
newExternalAccount.clientUserId = data.clientUserId;
newExternalAccount._metadata = { leadId: data.leadId };
if (data.code === 'f') {
query.searchSourceId = '5744f0925db77e3e42136924';
} else {
query.searchSourceId = data.searchSourceId;
}
newExternalAccount.searchSourceId = query.searchSourceId;
console.log('creating external account')
createExternalAccountSync(query, newExternalAccount)
.then(function (external) {
console.log('should return to meteor call');
return external;
})
.catch(function (e) {
console.error(e);
throw new Meteor.Error(e);
});
}
});
The problem that I'm having is that the code on the server side, while it's being called properly, is not triggering the client side meteor.call, there's no console.log output or anything. I believe that the Meteor.wrapAsync method is properly used, but still not showing anything on the client side, and not in fact redirecting where I want the user to go after form submission.
UPDATE
The code has being updated to the newest form, but now I'm getting a weird error on the client, and its actually because the meteor.call method on the template returns neither error or result
Exception in delivering result of invoking 'createExternalAccount': http://localhost:3000/app/app.js?hash=c61e16cef6474ef12f0289b3f8662d8a83a184ab:540:40
http://localhost:3000/packages/meteor.js?hash=ae8b8affa9680bf9720bd8f7fa112f13a62f71c3:1105:27
_maybeInvokeCallback#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3557:21
receiveResult#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3577:30
_livedata_result#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:4742:22
onMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:3385:28
http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:2736:19
forEach#[native code]
forEach#http://localhost:3000/packages/underscore.js?hash=27b3d669b418de8577518760446467e6ff429b1e:149:18
onmessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:2735:15
dispatchEvent#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:175:27
_dispatchMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1160:23
_didMessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1218:34
onmessage#http://localhost:3000/packages/ddp-client.js?hash=27502404fad7fc072e57e8b0b6719f40d92709c7:1365:28
By the code you provided,it could be because you are calling different method.
You defined 'createAccount' but on client side you are calling 'createExternalAccount'

Meteor: collection.remove.(id) works but still catching a 500 error

The item gets deleted/removed from the DB, but the catch error is Internal Server Error.
event triggered:
Template.post.events({
'click .delete': function () {
Meteor.call("deleteJob", this._id, function (err, result) {
if (!err) {
console.log("meteor call to remove job was good");
Bert.alert("Poof! Job deleted from the site.", "success");
Router.go('/');
} else {
Bert.alert("Rrrrr. No worky. " + err.reason + " " + result, "danger");
console.log("meteor call was bad", err);
}
});
}
});
Method call:
Meteor.methods({
deleteJob: function (id) {
var post = Posts.findOne(id);
if (post.author !== Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
try {
var postId = Posts.remove(id);
return postId;
} catch (exception) {
// If an error occurs, return it to the client.
return exception;
}
}
});
The remove() in the try should never return if there is a catch, right?
SOLVED
I'm using two packages that are checking my arguments. #didntKnow
check
audit-argument-checks
Keep an eye on your terminal window, peeps.
I needed this first in my method:
check(id, String);
Giving me this as the solution:
Meteor.methods({
deleteJob: function (id) {
check(id, String);
var post = Posts.findOne(id);
if (post.author !== Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
try {
var postId = Posts.remove(id);
return postId;
} catch (exception) {
// If an error occurs, return it to the client.
return exception;
}
}
});

Unable to invoke Meteor Call function

SERVER
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
}
Meteor.methods({
getApiResult: function() {
try {
var pipeline = [{$match: {"ACTIVE": 1}}, {"$group": {"_id": "$VARIENTS.NAME"}}, {
"$project": {
"_id": 0,
"TEMPLATE_NAME": "$_id"
}
}];
console.log("display pipeline");
console.log(pipeline);
var result = nodeDB.aggregate(pipeline);
console.log("display result", result);
for (i = 0; i < result.length; i++) {
var Temp_Name = result[i];
console.log("temp name is ", Temp_Name);
//productDB.insert({ Temp_Name: $(". Temp_Name").val()});
return result;
}
}catch (_error) {
return false;
}
});
}
}
CLIENT
if (Meteor.isClient) {
//error here **Meteor.call**('getApiResult', function(err, result) {
if (result) {
console.log("reached meteor call")
console.log(result);
}
});
};
ERROR:
Unexpected identifier at the line marked
You have a lot of problems with the sintaxis!
Server
if (Meteor.isServer) {
Meteor.startup(function () {
});
Meteor.methods({
getApiResult: function() {
try {
var pipeline = [{$match: {"ACTIVE": 1}}, {"$group": {"_id": "$VARIENTS.NAME"}}, {
"$project": {
"_id": 0,
"TEMPLATE_NAME": "$_id"
}
}];
console.log("display pipeline");
console.log(pipeline);
var result = nodeDB.aggregate(pipeline);
console.log("display result", result);
for (i = 0; i < result.length; i++) {
var Temp_Name = result[i];
console.log("temp name is ", Temp_Name);
//productDB.insert({ Temp_Name: $(". Temp_Name").val()});
return result;
}
}catch (_error) {
return false;
}
}
});
}
Client
if (Meteor.isClient) {
Meteor.call('getApiResult', function(err, result) {
if (result) {
console.log("reached meteor call")
console.log(result);
}
});
};
if (Meteor.isClient) {
//error here **Meteor.call**('getApiResult', function(err, result) {
if (result) {
console.log("reached meteor call")
console.log(result);
}
// }); // remove line Meteor.call end
};
remove Meteor.call end });

Cannot call method 'create' of undefined

Here is what I'm getting from the console server side.
I20140516-21:27:12.142(0)? There was an error on this page. Cannot call method 'create' of undefined
I am not finding a good reason why this method isn't defined. I have the balanced-payments-production package from Atmosphere loaded and this includes the balanced.js file and the api export to the server. Any help here is appreciated.
Here is my events.js file
Template.CheckFormSubmit.events({
'submit form': function (e, tmpl) {
e.preventDefault();
var recurringStatus = $(e.target).find('[name=is_recurring]').is(':checked');
var checkForm = {
name: $(e.target).find('[name=name]').val(),
account_number: $(e.target).find('[name=account_number]').val(),
routing_number: $(e.target).find('[name=routing_number]').val(),
recurring: { is_recurring: recurringStatus },
created_at: new Date
}
checkForm._id = Donations.insert(checkForm);
Meteor.call("addCustomer", checkForm, function(error, result) {
console.log(error);
console.log(result);
// Successful tokenization
if(result.status_code === 201 && result.href) {
// Send to your backend
jQuery.post(responseTarget, {
uri: result.href
}, function(r) {
// Check your backend result
if(r.status === 201) {
// Your successful logic here from backend
} else {
// Your failure logic here from backend
}
});
} else {
// Failed to tokenize, your error logic here
}
// Debuging, just displays the tokenization result in a pretty div
$('#response .panel-body pre').html(JSON.stringify(result, false, 4));
$('#response').slideDown(300);
});
var form = tmpl.find('form');
//form.reset();
//Will need to add route to receipt page here.
//Something like this maybe - Router.go('receiptPage', checkForm);
},
'click [name=is_recurring]': function (e, tmpl) {
var id = this._id;
console.log($id);
var isRecuring = tmpl.find('input').checked;
Donations.update({_id: id}, {
$set: { 'recurring.is_recurring': true }
});
}
});
Here is my Methods.js file
function getCustomer(req, callback) {
try {
balanced.marketplace.customers.create(req, callback);
console.log(req.links.customers.bank_accounts);
}
catch (error){
var error = "There was an error on this page. " + error.message;
console.log(error);
}
}
var wrappedGetCustomer = Meteor._wrapAsync(getCustomer);
Meteor.methods({
addCustomer: function(formData) {
try {
console.log(formData);
return wrappedGetCustomer(formData);
}
catch (error) {
var error = "There was an error on this page." + error.message;
console.log(error);
}
}
});
I needed to run balanced.configure('APIKEYHERE'); first, then run the balanced code.

Can't wait without a fiber

I'm using the node-imap meteor package to retrieve an email, then use that email to find a guest in a Guests collection. I get the "can't wait without a fiber error" when I include the Guest.findOne code. Here's the code
function openInbox(cb) {
imap.openBox('INBOX', true, cb);
}
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS (FROM SUBJECT DATE)','TEXT'] });
f.on('message', function(msg, seqno) {
console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
if (info.which === 'TEXT')
console.log(prefix + 'Body [%s] found, %d total bytes', (info.which), info.size);
var buffer = '', count = 0;
stream.on('data', function(chunk) {
count += chunk.length;
buffer += chunk.toString('utf8');
if (info.which === 'TEXT')
console.log(prefix + 'Body [%s] (%d/%d)', (info.which), count, info.size);
});
stream.once('end', function() {
if (info.which !== 'TEXT') {
console.log(prefix + 'Parsed header: ');
var header = Imap.parseHeader(buffer);
var from = header.from;
email = from[0].slice(from[0].indexOf('<')+1, from[0].indexOf('>'));
fetched = true;
}
else
console.log(prefix + 'Body [%s] Finished', (info.which));
});
});
msg.once('attributes', function(attrs) {
console.log(prefix + 'Attributes: %s', (attrs, false, 8));
});
msg.once('end', function() {
console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
if(fetched){
var guest = Guests.findOne({email: email}, {reactive: false}); // <-- this code causes the error
if(guest){
console.log(guest)
}
}
});
});
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
imap.connect();
So I tried to do a Meteor.bindEnvironment based on Future.wait() can't wait without a fiber (while waiting on another future in Meteor.method)
function openInbox(cb) {
imap.openBox('INBOX', true, Meteor.bindEnvironment(cb));
}
And get the error message "Cannot read property '_meteor_dynamics' of undefined". So there is no Fiber to bind to? I am still fairly new to Meteor so don't really know where to go from here. An explanation on what is going on and a solution would be great. Any help is appreciated.

Resources