I'm using Bookshelf
in my NodeJs
application for database manipulation
我在NodeJs应用程序中使用了Bookshelf来进行数据库操作。
I need when I execute:
我执行时需要:
User = bookshelf.Model.extend({
tableName: 'users'
});
new User({
firstName: "John",
lastName: "Paul"
}).save();
It will need saving values in 'first_name' and 'last_name' columns
它需要在“first_name”和“last_name”列中保存值
How to can I do define this?
我怎么定义这个呢?
1 个解决方案
#1
4
Apparently there is no built in method to do this. However I just asked this in #bookshelf irc and somebody told me :)
显然没有内置的方法来实现这一点。然而,我在#bookshelf irc上问过这个问题,有人告诉我:
var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g);
var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g);
var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g);
function camelize(str) {
return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
}).replace(/^([A-Z])/, function(match, separator, chr) {
return match.toLowerCase();
});
}
function underscore(str) {
return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').
replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase();
}
var _ = require('lodash');
var Podcast = bookshelf.Model.extend({
parse: function(attrs) {
return _.reduce(attrs, function(memo, val, key) {
memo[camelize(key)] = val;
return memo;
}, {});
},
format: function(attrs) {
return _.reduce(attrs, function(memo, val, key) {
memo[underscore(key)] = val;
return memo;
}, {});
}
});
var p = new Podcast();
p.set('lastUpdated', new Date());
To elaborate, this will turn camelCase into snake_case.
详细说明一下,这将使camelCase变成snake_case。
#1
4
Apparently there is no built in method to do this. However I just asked this in #bookshelf irc and somebody told me :)
显然没有内置的方法来实现这一点。然而,我在#bookshelf irc上问过这个问题,有人告诉我:
var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g);
var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g);
var STRING_UNDERSCORE_REGEXP_2 = (/\-|\s+/g);
function camelize(str) {
return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) {
return chr ? chr.toUpperCase() : '';
}).replace(/^([A-Z])/, function(match, separator, chr) {
return match.toLowerCase();
});
}
function underscore(str) {
return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').
replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase();
}
var _ = require('lodash');
var Podcast = bookshelf.Model.extend({
parse: function(attrs) {
return _.reduce(attrs, function(memo, val, key) {
memo[camelize(key)] = val;
return memo;
}, {});
},
format: function(attrs) {
return _.reduce(attrs, function(memo, val, key) {
memo[underscore(key)] = val;
return memo;
}, {});
}
});
var p = new Podcast();
p.set('lastUpdated', new Date());
To elaborate, this will turn camelCase into snake_case.
详细说明一下,这将使camelCase变成snake_case。