Answer the question
In order to leave comments, you need to log in
How to do proper insert in mysql + node.js?
I'm trying to make a competent creation of a table if if it does not exist when the data is first written to it, but the code turned out not very beautiful, can I write better?
insert(tableName, values) {
return new Promise((resolve, reject) => {
this.pool.query(`INSERT INTO ${tableName}(username, password, image) VALUES('${values.join("', '")}')`)
.then(resolve)
.catch(err => {
// if TABLE doesn't exists
if (err.errno == 1146) {
this.createTable(tableName)
.then(newTable => {
console.log("New table created!\n", newTable);
this.insert(tableName, values)
.then(resolve)
.catch(reject);
})
.catch(reject);
}
});
});
}
Answer the question
In order to leave comments, you need to log in
I would try something like this:
function insert(tableName, values) {
return this.pool.query(`INSERT INTO ${tableName}(username, password, image) VALUES('${values.join("', '")}')`)
.catch(err => {
// if TABLE doesn't exists
if (err.errno == 1146) {
return this.createTable(tableName)
.then(newTable => {
console.log('New table created!\n', newTable);
return this.insert(tableName, values);
})
} else {
throw err;
}
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question