How to alter a value before storing it to the database in Keystone JS

江枫思渺然 提交于 2019-12-23 05:29:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!