My challenge lies in updating a document within my event schema after a successful order is placed. My goal is to set 'isPurchased' to true so the product is no longer available for purchase, but despite my efforts, it remains false. Can someone help me identify what I'm doing incorrectly here?
Below is the action:
export const createOrder = async (order: CreateOrderParams) => {
try {
await connectToDatabase();
const eventId = order.eventId
const updatedEvent = await Event.findOneAndUpdate(
{eventId},
{ $set: { isPurchased: true } },
{new:true}
)
const newOrder = await Order.create({
...order,
event: order.eventId,
buyer: order.buyerId,
});
console.log(updatedEvent)
return {
order: JSON.parse(JSON.stringify(newOrder)),
updated: JSON.parse(JSON.stringify(updatedEvent))
}
} catch (error) {
handleError(error);
}
}
Here is the schema for the 'Event' model:
import { Document, Schema, model, models } from "mongoose";
export interface IEvent extends Document {
_id: string;
title: string;
seatInfo: string;
location: string;
createdAt: Date;
startDateTime: Date;
ticketUrl:string;
price: string;
quantity: string;
seller: { _id: string, firstName: string, lastName: string };
isPurchased:boolean;
}
const EventSchema = new Schema({
title: { type: String, required: true },
seatInfo: { type: String },
location: { type: String },
createdAt: { type: Date, default: Date.now },
startDateTime: { type: Date, default: Date.now },
ticketUrl: {type: String },
price: { type: String },
quantity: {type: String },
seller: { type: Schema.Types.ObjectId, ref: 'User' },
isPurchased: {type:Boolean, default:false}
})
const Event = models.Event || model('Event', EventSchema);
export default Event;
Lastly, here are the parameters used in the action:
export type CreateOrderParams = {
stripeId: string
eventId: string
buyerId: string
totalAmount: string
createdAt: Date
}
I have tried both findOneAndUpdate and findByIdAndUpdate methods, but neither is changing 'isPurchased' to true. The order is successfully created in the MongoDB Database, but this specific update seems to be unsuccessful.