Reputation: 373
Explanation
I am making a vpn app, and I'm trying to model the order with the plans. Each order has a virtual field array of plans. When a plan is created, it must reference an order so that the populate works. I know I can limit the amount of plans shown when I populate, but I want to limit the amount of plans created for each order to stop spam. So if the limit is 10 plans, if someone tries to create an 11th plan with the same order reference, it will throw an error.
sample:
Here is my orderSchema:
const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: [true, "Please provide a user for this order"],
},
//... other fields
}
);
// This is the array of plans connected to this order
orderSchema.virtual("plans", {
foreignField: "order",
localField: "_id",
ref: "Plan",
});
Here is my planSchema:
const planSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.ObjectId,
required: [true, "Please provide a user for this plan"],
ref: "User",
},
order: {
type: mongoose.Schema.ObjectId,
required: [true, "Please provide an order to process this plan"],
ref: "Order",
},
type: {
type: String,
enum: {
values: ["oneMonth", "sixMonth", "oneYear"],
message: "Plan type must be one of the following: 'oneMonth', 'sixMonth', 'oneYear'",
},
required: [true, "Please provide the type of plan"],
},
//... other fields
}
);
Extra thoughts: Could there be some sort of index that limits the order field to have 10 of the same ones? If not, totally fine, I just need a solution to this, thanks.
Upvotes: 0
Views: 33
Reputation: 2359
before adding new plan to order you should send query to plan
collection
to find number of plan with orderId and userId if the number is less than 10
add new plan
1 - query to find user and orderId
2 - if number of plans is less than 10 create else return false
app.post('/create',(req,res)=>{
var numberOfPlans = await plans.find({user:userId,order:orderId}).countDocuments()
if (numberOfPlans < 10) {
plans.create({data})
res.json({status:true})
}
else {
res.json({status:false})
}
})
Upvotes: 2