Laravel import excel error Undefined offset: 1 - excel

I tried to import excel to my mySql DB and am facing this error Undefined offset: 1
I have search everywhere, no related answers could resolve mine.
Here is my model
public function model(array $row)
{
return new Medicine([
'name' => $row[0],
'dosage_form' => $row[1],
'dosage_strength' => $row[2],
'product_date' => $row[3],
'expire_date' => $row[4],
'unit' => $row[5],
'serial_no' => $row[6],
]);
my Controller
public function import()
{
Excel::import(new MedicineImport, storage_path('Book1.xlsx'));
return redirect('Subscriber/importExcel')->with('success', 'All good!');
}
here is my excel screenshot

Have you tried doing a
var_dump($row)
and see if all the indices are properly set (especially index 1)?

Related

Error code 42601 in postgreSQL pg-promise, in NodeJS

I'm trying to make a bulk Insert/Update data in a db, but I have got this error, I don't know why, this is my code
This is the function of the promise of the bulkInsert
async bulkInsertFeatureTreatment(req, res) {
const { featuresTreatments } = await decryptRequest(req);
await db
.tx((t) => {
const queries = featuresTreatments.map((featureTreatment) => {
return t.none(
featuresTreatmentsDB.insertFeatureTreatment(featureTreatment)
);
});
return t.batch(queries);
})
.then((data) =>
cryptedResponse(res, response(200, INSERT_DATA_SUCCESS, data))
)
.catch((error) =>
cryptedResponse(res, response(500, INSERT_DATA_NOT_SUCCESS, error))
);
}
this is the function of insert/update, the upper function calls this
insertFeatureTreatment: (featuresTreatments) =>
`INSERT INTO ${TABLE_NAME} (${COL_ID_TREATMENT}, ${COL_ID_FEATURE}, ${COL_VALUE})
VALUES ('${featuresTreatments.id_treatment}', '${featuresTreatments.id_feature}', '${featuresTreatments.value}')
ON CONFLICT (${COL_ID_TREATMENT}, ${COL_ID_FEATURE})
DO UPDATE ${TABLE_NAME}
SET ${COL_VALUE} = '${featuresTreatments.value}'
WHERE ${COL_ID_TREATMENT} = '${featuresTreatments.id_treatment}'
AND ${COL_ID_FEATURE} = '${featuresTreatments.id_feature}'`,
Ok, that was a syntax error, it were about the conflict syntax, so this is the result:
insertFeatureTreatment: (featuresTreatments) =>
INSERT INTO ${TABLE_NAME} (${COL_ID_TREATMENT}, ${COL_ID_FEATURE}, ${COL_VALUE}) VALUES ('${featuresTreatments.id_treatment}', '${featuresTreatments.id_feature}', '${featuresTreatments.value}') ON CONFLICT (${COL_ID_TREATMENT}, ${COL_ID_FEATURE}) DO UPDATE SET ${COL_VALUE} = '${featuresTreatments.value}',

MongoDB insertMany BulkWriteError, avoid catch if duplicate key and perform then function

I'm importing multiple items in DB calling with a cron job the following function:
async function importItems(items){
return item_schema.insertMany(items, {ordered: false})
.then(docs => {
const n = docs ? docs.length : 0
docs.map((item) => {
/* Do something */
})
return `New items imported ${n} / ${items.length}`
})
.catch(error(500, `Error importing items.`))
}
Since a few of items could be previously imported, I'm getting the BulkWriteError due to duplicate key ('item_id') that always trigger catch.
My problem is that I need to "do something" with the n new items successfully imported that I get in the docs array in then function, ignoring the catch.
Is there any way to do that?
Thanks
function importItems(items) {
return item_schema.find({
item_id: {
$in: items.map((item) => item.item_id) // Check if item_id is one of the array values
}
})
.then((documents) => {
// documents is all the items that already exists
const newItems = items.filter((item) => !documents.find((doc) => doc.item_id === item.item_id));
return item_schema.insertMany(newItems, { ordered: false })
.then((docs) => {
const n = docs ? docs.length : 0
docs.map((item) => {
/* Do something */
})
return `New items imported ${n} / ${items.length}`
})
.catch(error(500, `Error importing items.`));
})
.catch(error(500, `Error importing items.`));
}

What's the difference between Promise.reject an error and Promise.reject object?

I was reading some nodejs tutorial which talks about rejection in nodejs. They say that it's best practice to reject an error instead of a string or an plain text. Taking example of this code.
This is a example of rejecting a string
function cookMeat(chef){
grillMeat(chef)
.then(meat => {
if(chef.isTired){
return Promise.reject(chef.tiredReason);
}
return Promise.resolve(meat);
})
}
function cookNoodle(cheif){
boilNoodle(chef)
.then(noodle => {
if(chef.isTired){
return Promise.reject(chef.tiredReason);
}
return Promise.resolve(noodle);
})
}
function cook(){
let chef
prepareFood()
.then(c => {
chef = c;
return true;
})
.then(() => cookMeat(chef))
.then(() => cookNoodle(chef))
.catch(err => {
state: Fail,
reason: error
})
.then(res => {
state:Ready
})
}
cook()
.then((res) => serveCustomer(res))
And this is a example of rejecting an error
function cookMeat(chef){
grillMeat(chef)
.then(meat => {
if(chef.isTired){
return Promise.reject(new Error(chef.tiredReason));
}
return Promise.resolve(meat);
})
}
function cookNoodle(cheif){
boilNoodle(chef)
.then(noodle => {
if(chef.isTired){
return Promise.reject(new Error(chef.tiredReason));
}
return Promise.resolve(noodle);
})
}
function cook(){
let chef
prepareFood()
.then(c => {
chef = c;
return true;
})
.then(() => cookMeat(chef))
.then(() => cookNoodle(chef))
.catch(err => {
state: Fail,
reason: error.message
})
.then(res => {
state:Ready
})
}
cook()
.then((res) => serveCustomer(res))
Since I want to use reject to skip part of the promise chain. So I am wondering if there are any difference?
wPromise rejections are similar to throwing exceptions / error objects.
There are two rules that apply to throwing exceptions that apply here too:
In javascript, it's better to throw an Error object. Among other things, you will get stack information. It's also what most people expect when using a javascript code base.
Don't use exceptions for flow-control
The second one is such a common advice, you can google it verbatim and learn more. You're using Promise rejections as flow control and this is a bad idea.
Your functions can be rewritten a bit though. This is even better:
function cookMeat(){
grillMeat()
.then(meat => {
if(meat.isRaw){
throw new Error(meat.rawReason);
}
return meat;
});
}
function cookNoodle(){
boilNoodle()
.then(noodle => {
if(noodle.isRaw){
throw new Error(noodle.rawReason);
}
return noodle;
})
}
function cook(){
return prepareFood()
.then(() => cookMeat())
.then(() => cookNoodle())
.catch(err => {
state: Fail,
reason: error.message
})
.then(res => {
state:Ready
})
}
cook()
.then((res) => talkWithCustomer(res))
I got rid of your Promise.reject and Promise.resolve statements, because they are unneccary from within a then() function. The advice to use them only really applies 'outside' of then() chains.

Node code not blocking?

I have a constructor which fetches data from a DynamoDB using promisified dynogels to populate part of the object's properties.
So after instantiating an instance of that object, the property is not populated, here is an extract of the code:
export class QueryAuthoriser {
authPerms: [AuthPerms];
constructor (data: string) {
AuthPermsDDB.scan().execAsync().then ( (perms) => {
perms.Items.forEach(element => {
this.authPerms[element.name] = <AuthPerms> element.attrs
})
}).catch (err => {
console.log ('%%%%%%%%%%%%%% Err loading authPerms: ', err)
})
}
authFieldAccess (fieldName: string, args?:any): Promise<boolean> {
return new Promise ((resolve, reject) => {
console.log ('________________ authFieldAccess called for: ', fieldName)
console.log ('________________ this.authPerms entry: ', this.authPerms[fieldName])
resolve (true)
})
[...]
}
So when authFieldAccess method is called, the field this.authPerms is undefined. How can I fix this?
Thanks, I'm learning node and typescript the hard way :O
You generally don't want to carry out an asynchronous operation in a constructor because it complicates creating an object and then knowing when the async operation is done or if it had an error because you need to allow the constructor to return the object, not a promise that would tell you when the async operation was done.
There are several possible design options:
Option #1: Don't do any async operation in the constructor. Then, add a new method with an appropriate name that does the async operation and returns a promise.
In your case, you could make the new method be scan() that returns a promise. Then, you'd use your object by creating it and then calling scan and then using the returned promise to know when the data is valid.
I don't know TypeScript myself, so I'll give a modified version of your code, but the concept is the same either way whether it's TypeScript or plain Javascript:
export class QueryAuthoriser {
authPerms: [AuthPerms];
constructor (data: string) {
}
scan () {
return AuthPermsDDB.scan().execAsync().then ( (perms) => {
perms.Items.forEach(element => {
this.authPerms[element.name] = <AuthPerms> element.attrs
})
}).catch (err => {
console.log ('%%%%%%%%%%%%%% Err loading authPerms: ', err)
})
}
}
// usage
let obj = new QueryAuthoriser(...);
obj.scan(...).then(() => {
// the object is full initialized now and can be used here
}).catch(err => {
// error here
})
Option #2: Initiate the async operation in the constructor and use a promise in the instance data for the caller to know when everything is done.
export class QueryAuthoriser {
authPerms: [AuthPerms];
constructor (data: string) {
this.initialScan = AuthPermsDDB.scan().execAsync().then ( (perms) => {
perms.Items.forEach(element => {
this.authPerms[element.name] = <AuthPerms> element.attrs
})
}).catch (err => {
console.log ('%%%%%%%%%%%%%% Err loading authPerms: ', err)
})
}
}
// usage
let obj = new QueryAuthoriser(...);
obj.initialScan.then(() => {
// the object is full initialized now and can be used here
}).catch(err => {
// error here
});
Option #3: Use a factory function that returns a promise that resolves to the object itself.
export createQueryAuthorizer;
function createQueryAuthorizer(...) {
let obj = new QueryAuthorizer(...);
return obj._scan(...).then(() => {
// resolve with the object itself
return obj;
})
}
class QueryAuthoriser {
authPerms: [AuthPerms];
constructor (data: string) {
}
_scan () {
return AuthPermsDDB.scan().execAsync().then ( (perms) => {
perms.Items.forEach(element => {
this.authPerms[element.name] = <AuthPerms> element.attrs
})
}).catch (err => {
console.log ('%%%%%%%%%%%%%% Err loading authPerms: ', err)
})
}
}
// usage
createQueryAuthorizer(...).then(obj => {
// the object is fully initialized now and can be used here
}).catch(err => {
// error here
});
My preference is for option #3 for several reasons. It captures some shared code in the factory function that every caller has to do in the other schemes. It also prevents access to the object until it is properly initialized. The other two schemes just require documentation and programming discipline and can easily be misused.

Node js db2 module

I'm using that code
var ibmdb = require('ibm_db')
function executeSql(sql)
{
return new Promise( (resolve,reject) => {
ibmdb.open("DRIVER={DB2};DATABASE=SITRAN;...",(err,conn) => {
if (err) reject(Error(err))
conn.query(sql,(err,rows) => {
if (err) reject(Error(err))
console.log('length:',rows.length)
conn.close(() => { console.log('done'); resolve(rows); })
})
})
})
}
executeSql(sql)
.then((result) => { console.log('result:',result.length) })
The db2 part is working, it gives 1045 rows but the code is working strangely
length: 0
length: 1045
done
result: 0
I don't understand why length is displayed twice, one with 0 and one with 1045. And also why the resolve(rows) seems not working.
conn.query() is an asynchronous function which might explain the double console.log() behavior. As far as the weird behavior with resolve(), try resolve(rows.fetchAllSync()) instead.

Resources