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

Issue with TagCloud functionality when deployed on Vercel platform

Everything functions perfectly on my local machine, but once deployed to Vercel, the display disappears. I've double-checked the text, container, and TagCloud - all showing the correct responses. I even tried uninstalling and reinstalling TagCloud wit ...

The React type '{ hasInputs: boolean; bg: string; }' cannot be assigned to the type 'IntrinsicAttributes & boolean'

I recently started learning react and encountered an error while passing a boolean value as a prop to a component. The complete error message is: Type '{ hasInputs: boolean; bg: string; }' is not assignable to type 'IntrinsicAttributes & ...

Instructions on accessing a mongoose database model Schema from another model

I have created two different schemas, one for users in the user.js file and the other for products in the product.js file. In my user schema (user.js): var userSchema = new Schema({ firstname: { type: String, required: true }, ...

Next-generation Keystone mutation customization

Could someone please help me troubleshoot why my mutation is not functioning properly? I am using a Keystone-next backend, apollo-boost, and next.js. Despite having the fields in the state and setting them as variables, they are not being sent to the backe ...

Nextjs version 13 is throwing a TypeError due to trying to read properties from null, specifically trying to read the 'length' property

Currently, I am in the process of learning how to build a Next.js application through a helpful tutorial on Egghead. I've hit a roadblock at lesson 4, where the tutorial covers retrieving data from a Supabase database. I suspect that my issue may be ...

When testing the Next.js App locally, the APIs function properly. However, issues arise when attempting to deploy the app

Having trouble deploying my NextJS App APIs to Netlify. Everything runs smoothly locally, but I keep encountering this error when trying to deploy. https://i.sstatic.net/C8FUv.png ...

Struggling to fetch information with Angular HttpClient from an API that sends back a JSON response with an array

As a beginner in Ionic and Angular, I am attempting to call an API and then showcase the team names within the template of my project. Despite following numerous tutorials and videos, I seem to be stuck as the JSON response returns an object with results f ...

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

Sourcemaps experiencing major issues when using TypeScript and the browserify/gulp combination

Despite successfully generating sourcemaps from my build process using browserify with gulp, I encountered issues when trying to debug. Breakpoints would often jump to different lines in Chrome, indicating that the script was not pausing where it should. A ...

Finding all the keys in a collection that have a specific string value in mongodb

If I have a collection called A. I am looking to extract all keys from this collection that have a specific value, such as "hello" { "a": "its me hello", "b": "it does not have value", "c&q ...

Unable to determine model dependency in Nest

I encountered an issue where Nest is unable to resolve dependencies. The error message from the logger reads as follows: [Nest] 39472 - 17.08.2023, 05:45:34 ERROR [ExceptionHandler] Nest can't resolve dependencies of the UserTransactionRepository ( ...

``Is there a specific scenario where the use of getInitialProps is recommended when automatically redirecting from one

Within my application, I have set up an auto-redirect from the root directory '/' to '/PageOne' with the following code: const Home = () => { const router = useRouter(); useEffect(() => { router.push('/pageone', ...

Retrieving the current time in milliseconds since 1970 with MongoDB

I have a field in my MongoDB database that represents a timestamp as milliseconds since 1970. However, this value is stored as a long integer from Python. Now, I need to retrieve all entries made after a specific time. I have been struggling to find a way ...

Is it possible to utilize the $ symbol within the ngOnInit or constructor functions?

I recently encountered an issue while trying to use the dollar sign ($) in my constructor function, specifically within ngOnInit() and translate.instant. Here is a snippet of the code that caused the problem: declare var $: any; { var SelectedDevice = ...

In the CallableFunction.call method, the keyword "extends keyof" is transformed into "never"

In the following method, the type of the second parameter (loadingName) is determined by the key of the first parameter. (alias) function withLoading<T, P extends keyof T>(this: T, loadingName: P, before: () => Promise<any>): Promise<void ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

When utilizing the Map.get() method in typescript, it may return undefined, which I am effectively managing in my code

I'm attempting to create a mapping of repeated letters using a hashmap and then find the first non-repeated character in a string. Below is the function I've developed for this task: export const firstNonRepeatedFinder = (aString: string): strin ...

Creating self-referencing MongoDB schema with post routes in nodejs: A step-by-step guide

I am currently working on building a nested parent-child system where the child schema mirrors that of the parent. Below is the schema for the parent, where children refer back to the parentSchema: var mongoose = require("mongoose"); var parentSchema ...

The new next.js 13 experimental feature is throwing an error stating "map is not

I am currently experimenting with the latest version of next.js (ver.13) and trying to debug my code. I followed the documentation but still can't figure out what's causing the issue. The error message reads: photos.map is not a function async f ...

What is the most efficient way to dynamically load a script file before proceeding with the rest of the code execution?

In my Angular home.component.ts file, I have added the script loading code as shown below: export class HomeComponent { constructor() { this.loadDynamicScript(); } public loadDynamicScript() { var script = document.createElement(&a ...