Is there a way for me to modify a value in Mongoose?

I have been attempting to locate clients by their ID and update their name, but so far I haven't been successful. Despite trying numerous solutions from various sources online.

Specifically, when using the findOneAndUpdate() function, I am able to identify clients based on their "_id", however, I cannot seem to modify a person's name successfully.

`export const PATCH = async (request : NextRequest) => {    
    try {
        const data = await request.json();
        await ConnectDB();
        const url = request.url;
        const id = url.split('/').pop();
    
        const application = await Application.findOneAndUpdate({_id : id}, {$set: data}, {new: true})

        return NextResponse.json({ application, id, data }, { status: 200 });

    } catch (error) {
        return NextResponse.json({ message: "Application Cannot be updated"}, { status: 401 })
    }
}`

Answer №1

Reviewing the update document is essential.

An error will be triggered by the current form of the query, as indicated below.

test> t.findOneAndUpdate({_id : new ObjectId()}, {$set: 'some data'}, {new: true});

MongoServerError: Modifiers operate on fields but we found type string instead. For example: {$mod: {<field>: ...}} not {$set: "some data"}

To correct this issue, please adjust the query to adhere to this structure.

test> t.findOneAndUpdate({_id : new ObjectId()}, {$set: {key1: 'some data'}}, {new: true});

In addition, ensure that you utilize the error object in your catch block, as it is currently not being referenced.

} catch (error) {
        return NextResponse.json({ message: "Application Cannot be updated"}, { status: 401 })
    }

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

Having trouble with importing Mongoose schema in a Node.js application?

I keep encountering an error message during the import process in my basic workout app Exercise-Tracker-MERN\backend\models\exercise.model.js:1 (function (exports, require, module, __filename, __dirname) { import Schema from "mongoose"; i ...

I'm perplexed as to why my array remains empty despite assigning a value to it in my controller. (Just to clarify, I am working with AngularJS, not Angular)

I spent a whole day debugging this issue without any luck. Issue: this.gridOptions.data = this.allTemplatesFromClassificationRepo ; **this.allTemplatesFromClassificationRepo ** remains an empty array. I have already called the activate() function to assig ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

Having difficulty generating a file with an embedded document nested within

After completing a node.js + mongodb tutorial, I'm endeavoring to construct a small project. However, I've hit a roadblock. I am working on creating a basic ecommerce api. The database consists of a seller collection and an inventory collection. ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

Issue with Mongoose failing to generate a new document in MongoDB

I am developing an education portal website using Next.js and MongoDB (mongoose). The school admin has the ability to add important notices from their dashboard, which can be viewed by students in their own dashboard. Due to the nature of most mongoose ope ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Difficulty encountered when combining create-react-app with typescript and immutable.js

After realizing that create-react-app now supports typescript, I encountered some issues while trying to transfer my current codebase from react-scripts-ts. Most of my classes are based on Record and cannot be constructed anymore due to errors like: Cannot ...

Concise way to add or insert an element into an array, at a specific property of an object

I am working with an object of the ObjectOfArrays type: type ObjectOfArrays = { [id: string]: Array<string> }; Throughout my code, I need to add strings to the correct array based on the id. Currently, I am using the following approach: if (id i ...

Transform string enum type into a union type comprising enum values

Is there a way to obtain a union type from a typescript string enum? enum MyEnum { A = 'a', // The values are different from the keys, so keyof will not provide a solution. B = 'b', } When working with an enum type like the one sh ...

Trying out Angular2 service using a fabricated backend

Just a heads up: I know Angular2 is still in alpha and undergoing frequent changes. I am currently working with Angular2 and facing an issue with testing an injectable service that has a dependency on http. I want to test this service using a mock backend ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

Having trouble with a malfunctioning part of the API in my NodeJS code. Any suggestions on how to resolve the issue

I'm currently working on developing a REST API in NodeJS for an online store. Here's a snippet of my code for handling POST requests: router.post('/', (req, res, next) => { const order = new Order({ _id: new mongoose.Typ ...

Discover the process of accessing and setting values in Angular 8 to easily retrieve and manipulate data from any page!

Greetings! I am currently utilizing Angular 8 and I have a query regarding how to access the set value in any given page. Here is a snippet of my code: class.ts export class testClass { get test():string{ return this.sexe; } ...

Best practices for efficiently creating documents in Mongoose when dealing with fields containing an unpredictable number of items

After researching and experimenting with demo code and tests, I have been working on implementing a school management system. Now, I am seeking advice from experienced mongoose developers on the best practice for creating a schema that allows for flexibili ...

Convert a DateTime object to JSON using the Mongo C# driver's toJson

I have a dataset stored in MongoDB that looks like this: "trd" : ISODate("2003-12-08T00:00:00Z") Currently, I am retrieving data from Mongo as BsonDocument using the following approach: var builder = Builders<BsonDocument>.Filter; var ...

What are the recommended approaches for PassportJS authentication and organizing MongoDB database collections effectively?

I'm currently working on a project that involves using nodejs, express, and mongodb for the first time. To handle authentication, I've opted to use passport.js because of its flexibility and ease of integration. I appreciate the concept of Seria ...

Is there a way to go back to the previous URL in Angular 14?

For instance, suppose I have a URL www.mywebsite.com/a/b/c and I wish to redirect it to www.mywebsite.com/a/b I attempted using route.navigate(['..']) but it seems to be outdated and does not result in any action. ...

The issue I'm facing is that the data is not being sent from my Vue application using WebSockets. The error message states that the 'send' function is undefined. I am using a tech

Below is the code snippet that I'm having trouble with: initializeConnection: function () { this.socket = new WebSocket('ws://144.0.0.0:8080'); //IP Changed this.socket.onopen = function(event) { console.log("Connected to the Web So ...

Issue with Ionic 3 subscribes triggering repeatedly

I've been struggling with the code for an Ionic taxi app for a few weeks now. My main issue is that whenever the page loads, the subscription gets triggered multiple times along with other functions within it. The same problem occurs when any travel i ...