It is crucial to include the _id field in the findOneAndUpdate operation

In my code, I have a function that updates documents in mongoDB. After manipulating the data, I use mongoose's findOneAndUpdate function to update the desired document. To fetch only specific fields from the saved data, I set new:true and define an object named userReturnFormat for projection. Here is an example of the code:

const userReturnFormat = {
    email: 1,
    name: 1,
    surname: 1,
    _id: 0
}

const updatedUser = (await UserModel.findOneAndUpdate(
            { registerId: params.user.registerId },
            { $set: data },
            { new: true, projection: userReturnFormat }
        )) as User

In the userReturnFormat object, I specifically set the _id field to false. When I include {_id:0} in the projection, it successfully excludes the _id field. Although I attempted to directly specify the projection within the update operation, it still returned the _id field when marking any property as true. While I can remove the _id field using the delete operand after updating the document, I prefer to solely rely on the projection for this purpose.

{_id: 0 } used as a projection:

const updatedUser = (await UserModel.findOneAndUpdate(
            { registerId: params.user.registerId },
            { $set: data },
            { new: true, projection: { _id: 0 } }
        )) as User

RESULT:

{
  email: ‘<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066c5962696346637e676b766a212d2f">[email protected]</a>’,
  password: ‘HASHED_PASSWORD’,
  name: ‘JOHN’,
  surname: ‘DOE’,
  type: ‘example’,
  createdAt: 2024-01-03T12:57:20.972Z,
  updatedAt: 2024-01-04T07:30:27.153Z
}

Using the delete operand:

const updatedUser = (
            await UserModel.findOneAndUpdate({ registerId: params.user.registerId }, { $set: data }, { new: true, projection: userReturnFormat })
        )?._doc

delete updatedUser._id

RESULT:

{
  email: ‘<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42281d262d2702273a232f322e276c212d2f">[email protected]</a>’,
  name: ‘JOHN’,
  surname: ‘DOE’,
}

Answer №1

Consider using the select method:

await UserDocument.findBy(
   { uniqueId: userInfo.id },
   { $adjust: info },
   { current: true }
).filter(userFormat).execute();

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

After upgrading Expo, the React Native Auth Session ceased to function

During my use of Expo SDK 48, my app successfully implemented Google and Facebook authentication with a web browser-based authentication method. Functional code: type AuthResponse = AuthSession.AuthSessionResult & { params: { access_token ...

Discover properties of a TypeScript class with an existing object

I am currently working on a project where I need to extract all the properties of a class from an object that is created as an instance of this class. My goal is to create a versatile admin page that can be used for any entity that is associated with it. ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Tips for inserting a property into an array of objects when it matches the specified ID

As someone new to Angular, I am encountering an issue and would appreciate some help. Here is an array of objects I am working with: signals = [{ 'signalID': '123' },{ 'signalID': '233' },{ 'signalID': &apo ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

Using TypeScript to validate React Functional components

As I delve into TypeScript for a React app using next.js, I find myself grappling with how to properly type React components. One of my components looks like this... type Props = { children: JSX.Element; }; export default function SiteLayout({ children ...

Difficulty locating information in MongoDB using Node.js

When attempting to retrieve data from a mongo database, the entire object with all properties including _id and title is returned. However, I only require the title. How can I resolve this? Models and Mongo Schema const mongoose = require('mongoose& ...

Choose items from a nested array

This database object contains the following information: { "_id" : { "$oid" : "53a9ce071e24a7a0a4bef03a"} , "name" : "name4" , "sections" : [ { "id" : "sectionId1" , "subs" : [ { "name" : " ...

Abbreviation for ensuring type safety when combining properties from one object with another

Imagine we have an object x representing type X and an object y representing type Y. Is there a way to combine (assign all properties) of y into x in such a way that if Y is not a proper subset of X, the compiler raises an error? NOTE: While Object.assig ...

Customizing the text color of words that originated from a dropdown selection within an Angular textarea editor

My Process: Within my interface, I utilize both a dropdown menu and a textarea field. I input text into the textarea and select certain words from the dropdown menu to add to the textarea. I have successfully completed this task. The Issue at Hand: Now, ...

"The powerful trio of Moongose, expressjs, and node-webkit combine forces

I'm currently in the process of developing an app using node-webkit, with expressjs and mongoose as the foundation. As a newcomer to this technology stack, I've encountered some challenges. One specific issue involves my attempt to integrate a m ...

The if else statement is behaving in a manner that is completely contrary to my intentions

Within the controller, there is code that handles toggling the "like" status of a post. This is how it functions: Firstly, it checks if the user has already liked the post. If not found, it adds the like status. If found, it removes the existing like st ...

API Router in Express with TypeORM returning 404 error when handling POST request

I've encountered a tricky bug while attempting to make POST requests to a test endpoint on my local server. My approach involves using Insomnia to send a basic Register JSON POST request to http://localhost:5000/api/auth/register with the following d ...

Error in TypeScript: Module 'stytch' and its corresponding type declarations could not be located. (Error code: ts(2307))

I'm currently developing a Next.js application and encountering an issue while attempting to import the 'stytch' module in TypeScript. The problem arises when TypeScript is unable to locate the module or its type declarations, resulting in t ...

What is the process for obtaining the count of results based on the role that was created?

[ { "_id": '1', "title":'admin', "created":"0", }, { "_id": '2', "title":'vendor', "created":"1", }, { "_id": '3', "title":'cus', "created":"1", } ...

Tips for exporting a React Component without using ownProps in a redux setup with TypeScript

I'm currently working on a project using typescript with react-redux. In one of my components, I am not receiving any "OwnProp" from the parent component but instead, I need to access a prop from the redux state. The Parent Component is throwing an er ...

Is it possible to apply Mongodb aggregation filters across multiple collections?

My database includes two collections: bookings and invoices. I have created an aggregate and lookup query to filter the data based on specific conditions. Conditions for the bookings collection: Condition 1: Status must not be equal to 'Delivered&ap ...

When trying to use `express.json()` within a `mongoose.connect()` block, it seems to encounter

I am curious about something. Why does app.use(express.json) not function properly within mongoose.connect? Here is the first code snippet: mongoose.connect(DB, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { app.use(&ap ...

Ngrx reducer is failing to trigger even when the state is accurately configured

I am working with a basic state structure: { items: Item[] selectedItems: string[] } In my application, I have a list of items with checkboxes. When I select an item, the list state is updated to include that item in the selected items array. However, ...

My app.js failed to launch on Heroku, receiving a Code H10 status 503 error

Starting with some screenshots: https://i.sstatic.net/E0pyj.png https://i.sstatic.net/SkZDv.png https://i.sstatic.net/HJ3Iw.png https://i.sstatic.net/LKFv2.png The full error log is below: 2020-06-15T10:46:45.640400+00:00 heroku[web.1]: Starting pro ...