Trouble persisting changes in Mongoose with findOneAndUpdate method

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.

Answer №1

Before proceeding, verify the accuracy of your ID. If you only need to modify a single field, consider using this approach:

const selector = {_id:eventID}
const updatedEventInfo = await Event.findOneandUpdate(selector, { isActive: true },{new:true})

This code snippet will update the data if the selector is accurate, which can be confirmed by:

let result = await Event.findOne(selector)

If the returned object matches the selector, you're good to go.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular boilerplate and Twitter Bootstrap 3 make for a powerful combination in

I've been attempting to integrate Twitter Bootstrap 3 into this project found at https://github.com/ngbp/ngbp, but I haven't been able to find any information on how to do so. Could it be that: It's simply not possible It's not recomm ...

Being patient doesn't seem to involve waiting for outcomes in my operations

After conducting thorough research, it seems like a similar question has been asked before. I have come across seven operations that need to be executed in a specific order. Most of these operations are related to databases and might require some time to c ...

Updating object values within a while loop using JavaScript

I am facing an issue with managing an array of JavaScript objects that have a property 'table' with values table1, table2, table3, or table4. Each table should only accommodate 6 members. I have implemented a while loop to check if 'table1&a ...

Aggregated asynchronous actions in JavaScript

Currently, I am seeking the technical term for a specific feature. My graphical user interface (GUI) includes interactive graphics. Once a user engages with the GUI, I have a need to carry out a CPU-intensive task. However, due to frequent user input, I on ...

Tips for extracting specific information from a nested object in MongoDB

I am currently storing data for a NestJs based web application in MongoDB. My MongoDB data has the following structure: "gameId": "1a2b3c4d5e" "rounds": [ { "matches": [ { "match_id& ...

Where can I locate the version of the nodejs driver?

Hello all! I'm a new user on mongoLab and currently have a database connected with a sandbox plan using MongoDB version 3.2. I recently received a warning about the upcoming upgrade to MongoDB 3.4. After investigating the compatibility changes require ...

When text is wrapped within the <li> tag

In this div, the structure is as follows: <div class="box1" id="infobox"> <h2> Point characteristics: </h2> <div style="padding-left:30px" align="left"> <ul> <li class="infobox_list"><b>X value: </b>< ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

Image caption dynamically updated to match thumbnail caption using jQuery upon click event

My goal is to dynamically load the data-caption of thumbnail images when clicked, and then update the main image's data-caption when the main image is changed with a thumb image. I am currently struggling to make the data-caption update along with the ...

Aggregating documents in MongoDB based on specific criteria shared by all members of the group

I'm currently working with a set of example documents structured like this: /* 1 */ { "_id" : ObjectId("61c50482f176d72cb660baa3"), "answer" : "yes",... /* 2 */ { "_id" : ObjectId(&quo ...

What is the process of combining two objects in TypeScript?

As part of my project, I am using two different get requests. The first request returns data in the form of: department: string[] The second get request provides an object structured like this: globalObj: { count: number[], admin: { department: ...

Utilizing various search and filtering methods with Meteor and Mongodb

I am managing a simple collection with fields for name, last name, category, age, and city. I am looking for an efficient way to perform multiple search and filter operations on these elements within a table. For example, filtering by name and age, age and ...

Guide on retrieving the AWS IAM user in string/json format using STS GetCallerIdentity Caller JS/TS

I am attempting to retrieve the AWS IAM Arn user using the STS GetCallerIdentity API provided by Amazon. The following code successfully logs the correct data in the console. Nevertheless, I am encountering difficulty returning the data as a string or JSON ...

Tips for modifying a server that was previously established with node.js without the need to set up a fresh server

In my node.js function, I use puppeteer to gather data and then output it to a json file. The data being collected changes frequently, so I utilize setInterval to reset the function periodically. Within the function, I have the following code snippet: ...

"Is it possible to implement NextJS 14 internationalization for both server and client side

With the introduction of the App router in NextJS 13 and above, internationalization has become a bit more complex. Despite reading multiple guides on the subject, one thing remains unclear to me - do we need separate methods for handling translations on t ...

`Next.js project experiencing issues with scroll trigger functionality`

I've been working on a gsap animation with a scroll trigger, and while the animation itself functions fine, it's not triggering as expected. The AnimationEffect code involves using gsap and scrolltrigger to create the animation. The Hero section ...

"Encountering an incorrect password while trying to log in using Node.JS, Passport,

I've been following a tutorial on NodeJS, Passport, and Sequelize and so far it's been going well. The sign-up part is working as expected. However, I've run into an issue where logging in with an incorrect password still results in a succe ...

Assistance needed with connecting MongoDB to Raspberry Pi

As I dive into the world of web development, I've been following Colt Steele's course on Udemy. The class is going smoothly, and I'm working on building my own website on the side that I want to host on a Raspberry Pi 4 (I have both the 32-b ...

``The powerful combination of NextAuth and OneLogin integrated into a NodeJS and Express API

This pertains to a previous inquiry I made concerning my project. The scenario is as follows: I have developed a NextJS application that utilizes NextAuth with OneLogin for authentication and stores session data in Mongo Atlas. The app is hosted on Vercel. ...

Fixing the error that occurs when selecting an option from a dropdown menu on

I am encountering an issue with my HTML form: <form> <select> <option value="" selected>Select an option</option> <option value="Warrior">Warrior</option> <option value="Paladin">Palad ...