How to limit creation of documents with same parent reference #10656
arian-fallahpour
started this conversation in
General
Replies: 1 comment 4 replies
-
Add a const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: [true, "Please provide a user for this order"],
},
planCount: { type: Number, default: 0 }
//... other fields
}
); When you try to create a plan, first increment the const order = await Order.findOneAndUpdate({ orderId }, { $inc: { planCount: 1 } }, { returnDocument: 'after' });
if (order.planCount > 10) {
await Order.updateOne({ orderId }, { $set: { planCount: 10 } }, {});
throw new Error('Cannot have more than 10 plans');
}
await Plan.create(plan); |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
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:
User creates and order with ID: 1
User creates 10 plans with the order id:1
The order has 10 plans associated with it
User tries to create another plan with order id:1, but fails
Here is my orderSchema:
Here is my planSchema:
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.
Beta Was this translation helpful? Give feedback.
All reactions