Home > Software design >  JOI to validate that selling quantity less than buying quantity
JOI to validate that selling quantity less than buying quantity

Time:11-30

I have two mongoose schema for trading app, one is buySchema

const buySchema = new Schema({
    parentId: String,
    buyingPrice: {
        type: Number,
        min: [0, 'Price can\'t be negative']
    },
    sharesBought: {
        type: Number,
        min: [0, 'No. of Shares can\'t be negative']
    },
    day: { type: Date, default: Date.now },
    sells: [{
        type: Schema.Types.ObjectId,
        ref: 'Sell'
    }],
})

and other is sellSchema

const sellSchema = new Schema({
    sellingPrice:Number,
    sharesSold:Number,
    day: { type: Date, default: Date.now }
})

Now I want to make sure that sharesSold is never greater than sharesBought.

module.exports.sellSchema = Joi.object({
    sell: Joi.object({
        sellingPrice: Joi.number().min(0).required(),
        sharesSold: Joi.number().min(0).max(***'How to handle this part'***).required(),
        day: Joi.date().required()
    }).required()
})

I don't know how to write JOI schema condition such that max value for sharesSold is less than sharesBought? Please help

CodePudding user response:

This is not something you can validate with joi. Your joi schema is only accepting information about sold shares, it doesn't have access to user's already existing shares. For better security and consistency it needs to be done on the application logic where there is access to stored boughtShares information

  • Related