Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / E-commerce Cart with Mongoose
interview

Q1. How would you model an e-commerce cart in MongoDB?
Typically, you'd have a 'carts' collection where each cart belongs to a user. Cart document contains items array with productId, quantity, price at time of addition. You might also have a separate 'products' collection. This allows flexibility and easy updates.

Q2. What would a cart schema look like in Mongoose?
const cartSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, items: [{ productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, name: String, price: Number, quantity: { type: Number, default: 1 } }], updatedAt: { type: Date, default: Date.now } });

Q3. How do you add an item to the cart?
Find the cart by userId, then either push new item or update quantity:
const cart = await Cart.findOne({ userId }); const existing = cart.items.find(i => i.productId.equals(productId)); if (existing) { existing.quantity += quantity; } else { cart.items.push({ productId, name, price, quantity }); } await cart.save();

Q4. How do you calculate the total price?
Add a virtual or method to the schema:
cartSchema.virtual('total').get(function() { return this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0); });
Then cart.total gives the sum.

Q5. How do you handle stock validation during checkout?
During checkout, you need to check product quantities. This might involve transactions (if using replica sets) or two-phase commits. In a simple app, you can:
const session = await mongoose.startSession(); session.startTransaction(); try { // check and update stock for each item await session.commitTransaction(); } catch { await session.abortTransaction(); } finally { session.endSession(); }