RCRD_DSNT_EXIST while creating user event script with aftersubmit function - netsuite

I'm trying to write a user event script which loads the current record and populates a line item value through search after submit record. But, it is giving an error RCRD_DSNT_EXIST, even though the record exists.
function afterSubmit_SO(type){
try
{
//var record_type = nlapiGetRecordType();
var recordID = nlapiGetRecordId();
var context = nlapiGetContext();
var recordOBJ = nlapiLoadRecord('salesorder',recordID);
var source = context.getExecutionContext();
if(source == 'userinterface')
{
var line_count = recordOBJ.getLineItemCount('item');
nlapiLogExecution('DEBUG', 'line count ', line_count);
for(var i = 1; i <= line_count; i++)
{
var itemID = recordOBJ.getLineItemValue('item','item',i);
nlapiLogExecution('DEBUG', 'item ID', itemID);
var filter = new Array();
filter[0] = new nlobjSearchFilter('internalid', null, 'is', itemID);
var columns = new Array();
columns[0] = new nlobjSearchColumn('custitem_web_market_availability');
var a_search_results = nlapiSearchRecord('item',null,filter,columns);
if(a_search_results)
{
for(var x = 0; x < a_search_results.length; x++)
{
var item_web_availability = a_search_results[x].getText('custitem_web_market_availability');
nlapiLogExecution('DEBUG', 'value', item_web_availability);
}
} recordOBJ.setLineItemValue('item','custcol_web_item_availability',i,item_web_availability);
}
var submitID = nlapiSubmitRecord(recordOBJ, true, true);
}
}
catch(exception)
{
nlapiLogExecution('DEBUG','Exception Caught ','' + exception);
}
return true;
}```

It could be that your script is executing on the delete operation. I did not see any checking for this in the code you provided. If it is a delete operation then the after submit user event script wont be able to load the deleted record, this is why you get the error.
The type parameter of your afterSubmit function should contain the operation type. You can something like if (type == 'delete') { return true;} at the top of your script.

Related

Update Existing Line Item Values in Netsuite SuiteScript 2.0

No matter what I do, I can't update the line item values in an inbound shipment record. I have a ton of debug statements, and I know that I technically am at the correct line, but when I try to get or set values, they are empty.
I am working in dynamic mode, and so in order to loop, I found something online that said I needed to stringify the record. I see all the correct data, but any time I try to manipulate the values, it doesn't do anything, or the values are empty. I also keep getting asked to provide the required fields, but for this particular line, they are already there.
Here is my code:
function doPost(restletBody){
log.debug('Called from POST', restletBody);
var success = [],
errors = [];
restletBody.data.forEach(function(e)
{
try
{
//Inbound Shipment Stuff
var ibsID = e.ibShipments.inboundShipmentRecordID;
var containerNumber = e.ibShipments.containerNumber;
var memo = e.ibShipments.memo;
var cargoReturnDate = e.ibShipments.cargoReturnDate;
var billoflading = e.ibShipments.billoflading;
var quantityexpected = e.ibShipments.quantityexpected;
var destCountry = e.ibShipments.destCountry;
var actualdeliverydate = e.ibShipments.actualdeliverydate;
var expecteddeliverydate = e.ibShipments.expecteddeliverydate;
var poDueDate = e.ibShipments.poDueDate;
var shipmentstatus = e.ibShipments.shipmentstatus;
var factory = e.ibShipments.factory;
var vesselNumber = e.ibShipments.vesselNumber;
var actualshippingdate = e.ibShipments.actualshippingdate;
var expectedshippingdate = e.ibShipments.expectedshippingdate;
var vesselBookingNumber = e.ibShipments.vesselBookingNumber;
var bookingDate = e.ibShipments.bookingDate;
var recID = null;
if((ibsID == "" || ibsID == null) && (containerNumber != "" || memo != "" || cargoReturnDate != "" ||
billoflading != "" || quantityexpected != "" || destCountry != "" || actualdeliverydate != "" ||
expecteddeliverydate != "" || poDueDate != "" || shipmentstatus != "" || factory != "" || vesselNumber != "" ||
actualshippingdate != "" || expectedshippingdate != "" || vesselBookingNumber != "" || bookingDate != ""))
{
//Create a new record
log.debug('Create Record', "");
var rec =
r.create({
type: "inboundshipment",
isDynamic: true,
defaultValues: null
});
//Might need to save the record, then add the fields
recID = rec.save();
var i = 1;
}
else
{
log.debug('Update Record Instead', ibsID);
recID = ibsID;
}
var inboundShipmentUpdate = r.load({
type: 'inboundshipment',
id: recID,
isDynamic: true
});
//Get Values from purchase order
var poID = e.poID;
var poName = e.poName;
var poShipDate = e.poShipDate;
var poShipWindowStart = e.poShipWindowStart;
if(poShipWindowStart != "")
poShipWindowStart = new Date(poShipWindowStart);
else
poShipWindowStart = "";
var poShipWindowEnd = e.poShipWindowEnd;
if(poShipWindowEnd != "")
poShipWindowEnd = new Date(poShipWindowEnd);
else
poShipWindowEnd = "";
//Item Fields
var itemID = e.items.itemID;
var itemDisplayName = e.items.displayName;
var itemName = e.items.name;
//Get Values from inbound shipment entry
var shipmentnumber = e.ibShipments.shipmentnumber;
var bookingDate = e.ibShipments.bookingDate;
if(bookingDate != "")
bookingDate = new Date(bookingDate);
else
bookingDate = "";
var vesselBookingNumber = e.ibShipments.vesselBookingNumber;
var expectedshippingdate = e.ibShipments.expectedshippingdate;
if(expectedshippingdate != "")
expectedshippingdate = new Date(expectedshippingdate);
else
expectedshippingdate = "";
var actualshippingdate = e.ibShipments.actualshippingdate;
if(actualshippingdate != "")
actualshippingdate = new Date(actualshippingdate);
else
actualshippingdate = "";
var vesselNumber = e.ibShipments.vesselNumber;
var containerNumber = e.ibShipments.containerNumber;
var factory = e.ibShipments.factory;
var shipmentStatus = e.ibShipments.shipmentstatus;
var poDueDate = e.ibShipments.poDueDate;
var expecteddeliverydate = e.ibShipments.expecteddeliverydate;
if(expecteddeliverydate != "")
expecteddeliverydate = new Date(expecteddeliverydate);
else
expecteddeliverydate = "";
var actualdeliverydate = e.ibShipments.actualdeliverydate;
if(actualdeliverydate != "")
actualdeliverydate = new Date(actualdeliverydate);
else
actualdeliverydate = "";
var destCountry = e.ibShipments.destCountry;
var quantityexpected = e.ibShipments.quantityexpected;
var quantityreceived = e.ibShipments.quantityreceived;
var billoflading = e.ibShipments.billoflading;
var cargoReturnDate = e.ibShipments.cargoReturnDate;
if(cargoReturnDate != "")
cargoReturnDate = new Date(cargoReturnDate);
else
cargoReturnDate = "";
var memo = e.ibShipments.memo;
//Set Field Values
inboundShipmentUpdate.setValue('actualshippingdate', actualshippingdate);
inboundShipmentUpdate.setValue('actualdeliverydate',actualdeliverydate);
inboundShipmentUpdate.setValue('custrecord_kk_booking_date', bookingDate);
inboundShipmentUpdate.setValue('custrecord_kk_cargo_return_dt',cargoReturnDate);
inboundShipmentUpdate.setValue('expectedshippingdate',expectedshippingdate);
inboundShipmentUpdate.setValue('expecteddeliverydate',expecteddeliverydate);
inboundShipmentUpdate.setValue('shipmentmemo', memo);
inboundShipmentUpdate.setValue('externaldocumentnumber',containerNumber);
//inboundShipmentUpdate.setValue('shipmentstatus',shipmentStatus);
inboundShipmentUpdate.setValue('billoflading',billoflading);
inboundShipmentUpdate.setValue('custrecord_kk_vesselbooking_number',vesselBookingNumber);
inboundShipmentUpdate.setValue('vesselnumber',vesselNumber);
inboundShipmentUpdate.setValue('custrecord_kk_destination',destCountry);
log.debug("Inside Line Items", e.items.itemID + " " + poID);
//The item must be unique, so it cannot already be on the inbound shipment. Do not set the current sublist value to the item
//if it already exists
var objCurRecIBS = JSON.parse(JSON.stringify(inboundShipmentUpdate));
log.debug("objCurRecIBS", objCurRecIBS );
var objSublistsIBS = objCurRecIBS.sublists ? objCurRecIBS.sublists : '';
log.debug("objSublistsIBS", objSublistsIBS );
var objIBSItems = objSublistsIBS.items ? objSublistsIBS.items : '';
log.debug("objIBSItems", objIBSItems );
var itemLineCountIBS = Object.keys(objSublistsIBS.items).length; //First Item is an empty item
var itemPresent = false;
//First Item is an empty item, so start at 1
for (var k = 1; k < itemLineCountIBS; k++)
{
//This keeps coming back empty
var currentQuantity = inboundShipmentUpdate.getCurrentSublistValue({
sublistId: "items",
fieldId: "quantityexpected"
});
log.debug("Current Quantity", currentQuantity + "Line " + k );
//So does this
var currentItem = inboundShipmentUpdate.getCurrentSublistValue({
sublistId: "items",
fieldId: "shipmentitem"
});
log.debug("Current Item", currentItem + "Line " + k );
var currItemIDIBS = objIBSItems[Object.keys(objSublistsIBS.items)[k]].itemid;
log.debug("Current Line Item Id", currItemIDIBS);
var currentLineIBS = objIBSItems[Object.keys(objSublistsIBS.items)[k]];
log.debug("cURRENT iTEM IBS Line", currentLineIBS);
if(currItemIDIBS == itemID)
{
//Update the existing line, since it is already present
itemPresent = true;
log.debug("Current Item Exists in the IBS", itemPresent);
//This is empty, too
var linePO = inboundShipmentUpdate.getCurrentSublistValue({
sublistId: "items",
fieldId: "purchaseorder"
});
log.debug("Line PO: ", linePO);
var currentQuantity = inboundShipmentUpdate.getCurrentSublistValue({
sublistId: "items",
fieldId: "quantityexpected"
});
log.debug("Current Quantity", currentQuantity + "Line " + k );
var newQuantity = currentQuantity + 2;
log.debug("New Quantity", newQuantity );
inboundShipmentUpdate.selectLine({
sublistId: 'items',
line: k
});
inboundShipmentUpdate.setCurrentSublistValue({
sublistId: "items",
fieldId: "quantityexpected",
value: newQuantity
//quantityexpected
});
inboundShipmentUpdate.commitLine({sublistId:"items"});
log.debug("Inside SELECT Line Items", "Line Committed" );
}
}
if(!itemPresent)
{
log.debug("Inside Item Present Check", itemPresent);
inboundShipmentUpdate.setCurrentSublistValue({
sublistId: "items",
fieldId: "shipmentitem",
value: shipmentitem
});
inboundShipmentUpdate.setCurrentSublistValue({
sublistId: "items",
fieldId: "quantityexpected",
value: quantityexpected
});
log.debug("Inside Line Items", "Shipment ITEM Added " + shipmentitem );
inboundShipmentUpdate.commitLine({sublistId:"items"});
log.debug("Inside Line Items", "Line Committed" );
}
++i;
inboundShipmentUpdate.save();
}
catch(err)
{
var msg = '';
log.debug("There was an error", err);
}
})
return "";
}
Does anyone have any idea why everything is coming back empty for me when I try to use NetSuite's methods, but showing correctly when I read the actual record's JSON?
I made this much more difficult than I needed to. I used the findSublistLineWithValue function, and was able to get the correct line value (it WAS 0, for whatever reason the json of the object was coming back with two entries, the first being empty values, so I incorrectly assumed that was line 0). I also had to compare against an actual string instead of a value, or I would get -1.
var lineNumber = inboundShipmentUpdate.findSublistLineWithValue({
sublistId: 'items',
fieldId: 'itemid',
value: itemID.toString()
});
Once I did this, I was able to get the correct values using my other methods. I just really dumbed down my api calls, and that helped me figure out what was going on.

Can't find specific address for specific customer by internal id

I'm trying to find the specific address by internal id from specific customer. Currently I'm trying to fetch 'address1' and 'address2' columns.
function getAddrById(addressid,invcustomerid) {
try {
var filters = new Array();
filters[0] = new nlobjSearchFilter('internalid', null, 'is', invcustomerid);
var columns = new Array();
columns[0] = new nlobjSearchColumn('address1');
var searchResult = nlapiSearchRecord('customer', null, filters , columns);
debugger;
if (!searchResult || searchResult.length < 1) {
nlapiLogExecution('DEBUG', 'XML HEAD', 'not supported address');
return;
}
if(searchResult) {
for (var i = 0 ; i < searchResult.length; i++) {
alert(searchResult[i].getValue('address1'));
};
};
} catch(e) {
nlapiLogExecution('ERROR', 'Try/catch error', e.message);
}
}
... here I get all address subrecords for specific customer, but I want only one specified by internal id, not to list all associated addresses from the customer.
columns[0] = new nlobjSearchColumn('addr1');
should be:
columns[0] = new nlobjSearchColumn('address1');
From your own link, you should be using the internal id from 'Search Columns' list at the bottom of the record, not "Fields".

Making an async loop in node.js with sql

Here is what I'm trying to do:
Start a looping (10x)
Select on sql to return 1 register (select top 1 where 'running' is null)
Sql update 'running' status to 'running'
If the record is null, I access an API and get some data
The result is updated on the initial sql record (set running = 'ok')
End looping (start over)
Thing is, node.js does not wait for start over, it does everything at the same time. That way, 'running' is always null.
var express = require('express');
var app = express();
var c_MyApi = require('./controller/call_MyApi');
var mongo = require('./controller/crud_mongo');
var c_email = require('./controller/api_email_verify');
var c_sql = require('./controller/consulta_sql');
var MyLink = '',
id = 0;
for( var i = 0 ; i < 10 ; i++){
c_sql.busca().then(function(res) {
MyLink = res[0].MyLink;
id = res[0].id;
c_sql.marca(id).then(
c_MyApi.busca(MyLink, function(a) {
if (a == 0) {
c_sql.atualiza(id, 'sem_email', 's/e');
}
if (a == 1) {
c_sql.atualiza(id, 'link_errado', 'l/e');
} else {
for (var i = 0; i < a.length; i++) {
var email = a[i].address;
c_email.busca(email, function(e_valid) {
c_sql.atualiza(id, email, e_valid)
})
}
}
})
)
})
}
}
//consulta_sql.js
var sql = require("seriate");
var search = function() {
var exec = 'select top 1 MyLink, id from sys_robo_fila where done is null';
sql.setDefaultConfig(config);
return sql.execute({
query: exec
});
}
var usado = function(id) {
var exec = "update sys_robo_fila set done = 'r' where id = " + id + "";
sql.setDefaultConfig(config);
return sql.execute({
query: exec
});
}
var update = function(id, email, valid) {
var exec = "update sys_robo_fila set email = '" + email + "' , validacao = '" + valid + "' , done = 'ok' where id = " + id + "";
sql.setDefaultConfig(config);
return sql.execute({
query: exec
});
}
module.exports = {
busca: search,
atualiza: update,
marca: usado
}
Any sugestions?
The call to c_sql.busca() is returning a Promise immediately and then continuing on to the next loop before then() is called, which is why they seem to run at the same time (they are actually just running very quickly, but before the Promise is resolved.
If you want this to run synchronously, one loop at a time, I would recommend using a recursive function to not start the loop again until the Promises have resolved.
let count = 0;
function doSomething() {
// this returns immediately, before .then() executes
return c_sql.busca()
.then(() => {
// do some more stuff after c_sql.busca() resolves
return c_sql.busca();
})
.then(() => {
// increment your count
count += 1
if (count<10) {
// less than 10 runs call the function again to start over
return doSomething();
}
});
}
This article might be helpful in understanding Promises: https://medium.com/#bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8

Synchronous Call : Call 2nd function after 1st function is executed completely

I recently stating coding in node.js and might be a very simple question.
Trying to write a XML parser/validator to validate xml schema and values against values/ xpath stored in an excel sheet.
Now once the validation function is complete I want to call a printResult function to print final result. However if I try to call the function immediately after the first function .. its printing variables initial values and if called within the first which is iterating though the number of xpaths present in excel sheet and printing result with increments.
var mocha = require('mocha');
var assert = require('chai').assert;
var fs = require('fs');
var parseString = require('xml2js').parseString;
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var XLSX = require('xlsx');
var Excel = require("exceljs");
var should = require('chai').should();
var HashMap = require('hashmap');
var colors = require('colors');
require('/xmlValidator/dbConnect.js');
var map = new HashMap();
var elementMap = new HashMap();
var resultValue;
//console.log('hello'.green);
map.set("PASS", 0);
map.set("FAIL", 0);
map.set("INVALID_PATH", 0);
function computeResult(elementPath, result) {
var pass = map.get("PASS");
var fail = map.get("FAIL");
var invalidPath = map.get("INVALID_PATH");
elementMap.set(elementPath, result);
if (result == "PASS") {
pass++;
map.set("PASS", pass);
} else if (result == "FAIL") {
fail++;
map.set("FAIL", fail);
} else {
invalidPath++;
map.set("INVALID_PATH", invalidPath)
}
printResult();
}
function printResult() {
var pass = map.get("PASS");
var fail = map.get("FAIL");
var invalidPath = map.get("INVALID_PATH");
console.log(("PASS Count :" + pass).green);
console.log(("FAIL Count :" + fail).red);
console.log(("Inavlid Path :" + invalidPath).yellow);
elementMap.forEach(function(value, key) {
if (value == "INVALID_PATH")
console.log((key + ":" + value).yellow);
else if (value == "FAIL")
console.log((key + ":" + value).red);
else
console.log(key + ":" + value);
});
}
var workbook = new Excel.Workbook();
workbook.xlsx.readFile('utils/' + process.argv[2])
.then(function() {
var worksheet = workbook.getWorksheet(1);
worksheet.eachRow(function(row, rowNumber) {
//console.log(rowNumber);
var row = worksheet.getRow(rowNumber);
var dataPath1 = row.getCell("A").value;
var dataPath2 = row.getCell("B").value;
var dataPath = dataPath1 + dataPath2;
//console.log(dataPath);
var dataValue = row.getCell("D").value;
var flag = row.getCell("E").value;
//console.log(flag)
//console.log(dataValue);
if (!flag)
validate(dataPath, dataValue, rowNumber);
//else console.log("NOT EXECUTED" + rowNumber)
});
})
function validate(dataPath, dataValue, rowNumber) {
var fail = 0;
fs.readFile('utils/' + process.argv[3], 'utf8', function(err, data) {
if (err) {
console.log("ERROR ERROR ERROR ERROR ");
return console.log(err);
}
var doc = new dom().parseFromString(data);
var subId = String(xpath.select1(dataPath, doc));
if (subId == "undefined") {
/*console.log('undefined caught');
console.log("row number :" + rowNumber);*/
var resultValue = "INVALID_PATH";
computeResult(dataPath, resultValue);
} else {
var subId = xpath.select1(dataPath, doc);
var value = subId.lastChild.data;
/*console.log("row number :" + rowNumber);
console.log("actual value: " + value);
console.log("expected value:" + dataValue );*/
if (dataValue == null) {
assert.notEqual(value, dataValue, "value not found");
resultValue = "PASS";
computeResult(dataPath, resultValue);
} else {
if (value == dataValue)
resultValue = "PASS";
else resultValue = "FAIL";
computeResult(dataPath, resultValue);
}
}
});
}
In the code above i want to call printResult() function after validate function is completely executed (workbook.xlsx.readFile)
Can some one please help me out how to use done () function or make sync call ?
If fs.readFileAsync('utils/' + process.argv[3], 'utf8') can be executed once, then validate() will be completely synchronous and calling printResult() after the verification loop will be trivial.
In the main routine, you can simply aggregate two promises ...
var promise1 = workbook.xlsx.readFile();
var promise2 = fs.readFileAsync(); // requires `fs` to be promisified.
... before embarking on the verification loop.
Promise.all([promise1, promise2]).spread(/* verify here */);
Also a whole bunch of tidying can be considered, in particular :
establishing "PASS", "FAIL" and "INVALID_PATH" as constants to avoid lots of repetitive string creation,
using js plain objects in lieu of hashmap,
building map from elementMap inside the print function.
having validate() return its result and building elementMap in the main routine
Here's the whole thing, about as tight as I can get it. I may have made a few assumptions but hopefully not too many bad ones ...
var mocha = require('mocha');
var assert = require('chai').assert;
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); // allow Bluebird to take the pain out of promisification.
var parseString = require('xml2js').parseString;
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var XLSX = require('xlsx');
var Excel = require("exceljs");
var should = require('chai').should();
// var HashMap = require('hashmap');
var colors = require('colors');
require('/xmlValidator/dbConnect.js');
const PASS = "PASS";
const FAIL = "FAIL";
const INVALID_PATH = "INVALID_PATH";
function printResult(elementMap) {
var key, result,
map = { PASS: 0, FAIL: 0, INVALID_PATH: 0 },
colorNames = { PASS: 'black', FAIL: 'red', INVALID_PATH: 'yellow' };
for(key in elementMap) {
result = elementMap[key];
map[(result === PASS || result === FAIL) ? result : INVALID_PATH] += 1;
console.log((key + ": " + result)[colorNames[result] || 'black']); // presumably colors can be applied with associative syntax? If so, then the code can be very concise.
}
console.log(("PASS Count: " + map.PASS)[colorNames.PASS]);
console.log(("FAIL Count: " + map.FAIL)[colorNames.FAIL]);
console.log(("Inavlid Path: " + map.INVALID_PATH)[colorNames.INVALID_PATH]);
}
function validate(doc, dataPath, dataValue) {
var subId = xpath.select1(dataPath, doc),
value = subId.lastChild.data,
result;
if (String(subId) == "undefined") {
result = INVALID_PATH;
} else {
if (dataValue === null) {
assert.notEqual(value, dataValue, "value not found"); // not too sure what this does
result = PASS;
} else {
result = (value === dataValue) ? PASS : FAIL;
}
}
return result;
}
//Main routine
var workbook = new Excel.Workbook();
var promise1 = workbook.xlsx.readFile('utils/' + process.argv[2]); // from the question, workbook.xlsx.readFile() appears to return a promise.
var promise2 = fs.readFileAsync('utils/' + process.argv[3], 'utf8');
Promise.all([promise1, promise2]).spread(function(data2, data3) {
var worksheet = workbook.getWorksheet(1),
doc = new dom().parseFromString(data3),
elementMap = {};
worksheet.eachRow(function(row, rowNumber) {
// var row = worksheet.getRow(rowNumber); // row is already a formal variable ???
var dataPath, dataValue;
if (!row.getCell('E').value)
dataPath = row.getCell('A').value + row.getCell('B').value;
dataValue = row.getCell('D').value;
elementMap[dataPath] = validate(doc, dataPath, dataValue);
});
printResult(elementMap);
});
Untested so may not run but at least you can raid the code for ideas.

How to query two collection in mongoose on nodeJs?

hi am new to nodeJs i have to query a table from the result of the query, i have to query another table. i tried the code as follows but it returns only null.
action(function getpositions(req){
var namearray = [];
NHLPlayerStatsDaily.find ({"created_at": {$gt: new Date(y+"-"+m+"-"+d)}}, function(err,position){
if(!err)
{
for (i=0;i< position.length; i++)
{
var obj = JSON.stringify(position[i]);
var pos = JSON.parse(obj);
var p = pos["player_stats_daily"]["content"]["team_sport_content"]["league_content"]["season_content"]["team_content"]["team"]["id"]
NHLTeam.find({"sdi_team_id": p}, "first_name nick_name short_name sport_id", function(err, team){
if (!err){
var obj = JSON.stringify(team);
var pos = JSON.parse(obj);
namearray.push(team)
}
})
}
return send(namearray);
}
})
})
if i just push "p" it shows the result and when am query "NHLTeam" in separate function it also shows the result. when querying a collection with in collection it return null. how to query a collection within a collection in mongoose. thanks in advance.
This is not a query problem, it is callback issue. The send(namearray) is called before any of the NHLTeam queries in the loop are completed (remember the result of these queries is passed to callback asynchronously).
What you can do is this (basically tracking when all callbacks are completed):
NHLPlayerStatsDaily.find ({"created_at": {$gt: new Date(y+"-"+m+"-"+d)}}, function(err,position){
if(!err)
{
var total = position.length;
for (i=0;i< position.length; i++)
{
var obj = JSON.stringify(position[i]);
var pos = JSON.parse(obj);
var p = pos["player_stats_daily"]["content"]["team_sport_content"]["league_content"]["season_content"]["team_content"]["team"]["id"]
NHLTeam.find({"sdi_team_id": p}, "first_name nick_name short_name sport_id", function(err, team){
total--;
if (!err){
var obj = JSON.stringify(team);
var pos = JSON.parse(obj);
namearray.push(team);
}
if(total == 0)
send(namearray);
})
}
}
})

Resources