I am trying to update a sequelize model partially that contains a string array value separated by semicolons.
languages: {
type: Sequelize.STRING,
allowNull: false,
get() {
if (this.getDataValue('languages') === null) {
return [];
} else {
return this.getDataValue('languages').split(';');
}
},
set(val) {
if (val.length === 0) {
this.setDataValue('languages', null);
} else {
this.setDataValue('languages', val.join(';'));
}
},
},
I found a solution. Before updating the value it reads the current value and it gives as undefined when it is null in the database. By enhancing the if check it resolves the issue.
languages: {
type: Sequelize.STRING,
allowNull: false,
get() {
if (this.getDataValue('languages') === null || this.getDataValue('languages') === undefined) {
return [];
} else {
return this.getDataValue('languages').split(';');
}
},
set(val) {
if (val.length === 0) {
this.setDataValue('languages', null);
} else {
this.setDataValue('languages', val.join(';'));
}
},
},
Short answer
It is better to check if the variable is null
or undefined
, remember that both values are different. null
means nothing, null was assigned, whereas undefined
means a variable was declared but no value was assigned to it.
You could do that
if (!!this.getDataValue('languages')) {
return this.getDataValue('languages').split(';');
} else {
return [];
}
Long answer
If you want to intercept all your request and replace values, Eg: In case it is a nullable list, I want to display []
, In case it is a nullable boolean, I want to display false
.
You may want to use a middleware to do that.
It would be something like below code:
const app = express();
app.set("json replacer", (k, v) => {
return formatJSONNull(k, v);
});
var formatJSONNull = function (k, v) {
if (v === null || v === undefined) {
if (listValues.indexOf(k) >= 0) {
return [];
} else if (integerValues.indexOf(k) >= 0) {
return 0;
} else if (boolValues.indexOf(k) >= 0) {
return false;
} else {
return "";
}
}
return v;
};
const listValues = ['languages'];
const boolValues = ['language_count'];
const integerValues = ['language_count'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.