The field '_id' is not present in the type Pick

I'm working on a project using Next.js and attempting to query MongoDB with TypeScript and mongoose, but I keep encountering a type error.

types.d.ts

type dbPost = {
  _id: string
  user: {
    uid: string
    name: string
    avatar: string
  }
  post: {
    title: string
    description: string
    markdown: string
    slug: string
    createdAt: string
  }
}
export const getSlugData = async (slug: string) => {
  await dbConnect()

  const data:
    | Pick<dbPost, '_id' | 'post' | 'user'>
    // The issue seems to be arising here with Pick[]
    | Pick<dbPost, '_id' | 'post' | 'user'>[]
    | null = await Post.findOne({ 'post.slug': slug }).lean().select('-__v')

  const post = {
    ...data,
    _id: `${data._id}`,
    // _id and createdAt are objects created by mongoose that can't be serialized.
    // They need to be converted to strings
    post: {
      ...data.post,
      createdAt: `${data.post.createdAt}`,
    },
  }
  return post
}

I'm encountering the following error:

Property '_id' does not exist on type 'Pick<dbPost, "_id" | "post" | "user"> | Pick<dbPost, "_id" | "post" | "user">[]'.
  Property '_id' does not exist on type 'Pick<dbPost, "_id" | "post" | "user">[]'.ts(2339)

What am I doing wrong with Pick<>[]?

package.json

  "dependencies": {
    "mongoose": "^5.10.6",
...
  },
  "devDependencies": {
    "@types/mongoose": "^5.7.36",
...
  }

dbConnect() is a function taken from the Next.js examples

Answer №1

The reason for this issue is that you have specified to the compiler that data could potentially be an array, which would require different ways of accessing individual objects.

findOne does not retrieve an array; it simply returns either a Record<string, T> or null. Therefore, you should eliminate

Pick<dbPost, '_id' | 'post' | 'user'>[]
from your type union.

const data:
| Pick<dbPost, '_id' | 'post' | 'user'>
| null = await Post.findOne({ 'post.slug': slug }).lean().select('-__v')

It's crucial to acknowledge that data could still be null, so be sure not to access properties on a null value. The revised function:

export const getSlugData = async (slug: string) => {
  await dbConnect()

   const data:
    | Pick<dbPost, '_id' | 'post' | 'user'>
    | null = await Post.findOne({ 'post.slug': slug }).lean().select('-__v')

   // Verify if data is null
   const post = data && {
    ...data,
    _id: `${data._id}`,
    post: {
        ...data.post,
        createdAt: `${data.post.createdAt}`,
      },
    }
    return post
 }

For maintaining type consistency, ensure that the fields in your select align with those in your Pick<>.

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

Unable to link to 'amount' because it is not a recognized attribute of 'ng-wrapper'

I recently made some changes to my code and now I'm encountering the error message "Can't bind to 'count' since it isn't a known property of 'ng-container'" Instead of having both the notification component and notificat ...

When utilizing Rx.Observable with the pausable feature, the subscribe function is not executed

Note: In my current project, I am utilizing TypeScript along with RxJS version 2.5.3. My objective is to track idle click times on a screen for a duration of 5 seconds. var noClickStream = Rx.Observable.fromEvent<MouseEvent>($window.document, &apos ...

If you include react-multi-date-picker with the render prop set to <InputIcon />, it may trigger a warning in

Looks like the code is missing a function with that name. I followed the documentation and added the icon, but ended up receiving a warning. In next-dev.js:20 Warning: React is not recognizing the handleValueChange prop on a DOM element. To avoid this wa ...

The property 1 cannot be added because the object is not extendable in React

Does anyone know what is causing the following issue? I am unable to insert a new object into a key object within my arrays of objects. For example, when I try to insert a new email at index 1 in the 'emails' array, it throws an error stating "ca ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

Experiencing Issues with Data Submission to MongoDB: Encountering 500 Error and Missing Values

My issue arises when I click the submit button, it does send data to MongoDB but returns a 500 error as well. Furthermore, there is an issue where inputting user data (inside the HTML) results in sending null values. Can anyone provide assistance with this ...

How can I display input only when a checkbox is selected? React with Next.js

I'm trying to figure out how to handle this task, but I'm a bit confused on the approach. I would like to display the promo code field only when the checkbox (I have a promo code) is checked. Additionally, it would be ideal to reveal this field ...

What could be causing my react-lightbox to not expand to full screen in next.js?

I'm facing an issue in my next.js project where I am unable to view my gallery collection as expected. When clicking on an image, nothing happens as if it's just a regular component being used. Can someone please assist me with this problem? / ...

Attempting deletion with Node.js's Mongoose Framework

Having some trouble with the following code snippet. It doesn't seem to be functioning correctly and is resulting in a 404 error. Any insights on how to troubleshoot this issue? app.delete("/tm/v1/tasks", (req,res) => { Task.findOneAndDelete ...

Utilizing interpolation in Angular to apply CSS styling to specific sections of a TypeScript variable

Suppose I have a variable called data in the app.component.ts file of type :string. In the app.component.html file, I am displaying the value of data on the UI using string interpolation like {{data}}. My question is, how can I apply some css to specific ...

Expanding unfamiliar categories

Currently, I am working with Gutenberg blocks in a headless manner. Each Gutenberg block is defined by the following structure: type Block = { name: string; className?: string; key?: string | number; clientId: string; innerBlocks: Block ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

The layout in Next.js production builds appears to be distinct from the layout in the

Currently, I am working on a website where I have implemented a dark theme by adding a class to the body element. Everything is functioning perfectly in the development environment, but I am encountering issues in the production build. Here is the root l ...

The SrollToTop function is ineffective when used with a component in Ionic 6/Angular

Recently, I implemented a fabbutton feature that allows users to scroll to the top of a page with just one click. Initially, I tested this functionality without using it as a component, and everything worked perfectly. However, now I want to turn this fabb ...

Could you explain the distinction between npm install and sudo npm install?

I recently switched to using linux. To install typescript, I ran the following command: npm i typescript Although there were no errors during the installation process, when I checked the version by typing tsc --version, I encountered the error message -bas ...

What is the best way to execute a sequence of http requests only after the previous one has been completed successfully, while also addressing any

Working with Angular/rxjs 6 has brought me to a challenge. I'm struggling to get an observable sequence to run smoothly as intended. Here's the concept of what I'm trying to achieve: Request received to change systems: Check permissions Fe ...

Utilizing React Typescript to dynamically render a duo of components

On a single page, I want to display two components simultaneously. There is a bottom navbar that, when clicked on, for example the profile icon, should render the profile page. However, I would like to change the color of the icon based on which component ...

Encountering an issue with core.js:15723 showing ERROR TypeError: Unable to access property 'toLowerCase' of an undefined value while using Angular 7

Below, I have provided my code which utilizes the lazyLoading Module. Please review my code and identify any errors. Currently facing TypeError: Cannot read property 'toLowerCase' of undefined in Angular 7. Model Class: export class C_data { ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

Is there a way to modify the style when a different rarity is selected in Next.JS?

Is there a way to change the style depending on the rarity selected? I am currently developing a game that assigns a random rarity upon website loading, and I am looking to customize the color of each rarity. Here is how it appears at the moment: https:/ ...