Home > database >  Mongoose: How to Store Duration and Time?
Mongoose: How to Store Duration and Time?

Time:02-25

In Mongoose, how does a person save duration in the Mongo Database? I'm trying to make a tennis application, and am stuck on database design, specifically with time.

For example, I want to add a Rally event (just hitting the tennis ball back and forth with another player) for X amount of time. So I'd like to store duration.

Another example, when playing a game of tennis with someone else, I'd like to store the total duration of the game.

I'm thinking to compute the difference between end time and start time, but can you do math in Mongo?

const MatchSchema = new mongoose.Schema({
  startTime: {
        type: Date,
        default: Date.now
    },
    endTime: {
        type: Date
    },
    duration: {
        type : Date
    },
    player: {
        type: String,
        trim: true,
        require: [true, 'Please add a player name']
    },
    opponent: {
        type: String,
        trim: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    score: {
        playerOneScore: {
            type: Number        
        },
        playerTwoScore: {
            type: Number       
        }
    },
    category: {
        //array of strings
        type: [String],
        required: true,
        enum: [
            'Rally',
            'Set',
            'Match',
            'Practice'        
       ]
    }
});

module.exports = mongoose.model('Match', MatchSchema);

CodePudding user response:

Within mongoose you have access to Middleware (also called pre and post hooks) which allows to define some action which can be perform during different lifecycle of a query You can check the Post hook which allow you to perform certain action after the model have been saved to the database.

Here is how it's define

MatchSchema.post('save', function(doc, next) {
  // here you have access to the document which have been save to the database
}); 

As Schema are define in javascript and you have access to model which have been saved in the argument doc of the callback passed to the .post function you can perform whatever math calculation which are possible using javascript and make some changes to other attribute on the same document and save the update made to the database.

CodePudding user response:

(1) Date math is possible in MongoDB. See Aggregation Operators for Date.

(2) You can also store duration as a field of type number (an integer or long), but it will be something as you want in your application - in seconds or minutes. Name the field as duration_in_seconds, for example.

Another possibility is to store duration as:

duration: {
    hours: number,
    minutes: number,
    seconds: number
}
  • Related