问题
Keystone and mongo are both new to me, so I'm unsure how to manipulate data.
I have a Keystone list which has a model (/models/Game.js
) that looks like:
var keystone = require('keystone');
var Types = keystone.Field.Types;
var Game = new keystone.List('Game');
Game.add({
odds: { type: Types.Text, required: true, initial: true},
});
Game.track = true;
Game.defaultSort = '-createdAt';
Game.defaultColumns = 'odds';
Game.register();
The odds field is a string, e.g. 3/1
, and I want to run this through a function that splits it and returns a decimal version, for example:
function decimalOdds(fraction) {
const splitFields = fraction.split('/');
return ((splitFields[0] / splitFields[1]) + 1).toFixed(2);
}
It's the return value of that function that I want to be stored as the 'odds' in the data base. Is that possible?
回答1:
You can use a pre save hook:
Game.schema.pre('save', function(next) {
if (this.isModified('odds')) {
this.odds = decimalOdds(this.odds)
}
next()
})
You can read more in the schema plugins section of the docs: http://keystonejs.com/docs/database/#lists-plugins
You can also find more information on Mongoose schema hooks here: http://mongoosejs.com/docs/middleware.html
来源:https://stackoverflow.com/questions/46667631/how-to-alter-a-value-before-storing-it-to-the-database-in-keystone-js