Encountering Error with NextAuth When Querying User Model

Currently, I am using NextAuth for my Next.js/MongoDB application. However, I encountered an issue when attempting to query the User record in an Api file.

import Users from '../../../model/user';
let userId = query.id;
const userData = await Users.findOne({_id:userId});
console.log('userData ',userData);

The error message that I am receiving is as follows:

Error: _model_user__WEBPACK_IMPORTED_MODULE_1__.default.findOne is not a function

Answer №1

  1. What does the term query refer to in your code? Consider using req.query.id, as API requests and responses typically involve req and res

  2. Make sure to convert your userId to an ObjectId

    import Users from '../../../model/user';
    import { ObjectId } from 'bson';
    
     ...your handler method, such as get, post, delete etc
    
    //if your file is named [id].tsx, for [pid].tsx you should use req.query.pid
    let userId = req.query.id;
    
    //you only need to transform if searching by _id field
    const userData = await Users.findOne({"_id": ObjectId(userId)});
    if (userData.?_id){
     res.status(200).json(userData)
    }
    else{
     res.status(500).json('User data not found')
    }
    

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 functionality of Framer Motion Animate Presence is currently experiencing issues when used with the latest NextJS App Router's route interception feature

I'm attempting to develop a modal utilizing intercepting routes similar to the example shown in this guide on NextJS documentation. I am using framer motion for implementing modal animations, however Animate Presence seems to be causing issues in this ...

A Reference Error has been encountered in the file "bundle.js" located at "@polkadot/extension-dapp"

I attempted to create a basic user interface for smart contracts using polkadot.js within the next.js framework. The UI content is straightforward, calling the Flipper contract that serves as an example contract in substrate. Upon compiling, I encountered ...

Hovering over the Next.js Link component triggers a refresh

I have developed an ecommerce application using next.js. The top bar of the application contains contact and other link information, followed by a long search section below. These two items are implemented in 2 components and combined together. However, I ...

managing the reloading of pages and navigating back and forth in the browser

In my project, I am using react and next.js to make API requests from a search bar and display a list of movies on the homepage. Each search result redirects me to a different page that shows detailed data related to the selected movie. However, the issue ...

Having trouble displaying the correct data for the Title in NextJs Head? Any solutions available?

Hi there, I am currently utilizing the <Head/> Tag from an API in my NextJs project. All meta tags are functioning properly except for the title meta tag, which seems to be displaying the first H1 on the page instead. Here is the code snippet: ...

What is the best way to convert my Chatbot component into a <script> tag for seamless integration into any website using React.js?

I have successfully integrated a Chatbot component into my Next.js application. https://i.stack.imgur.com/BxgWV.png Now, I want to make this component available for anyone to use on their own website by simply adding a tag. My initial approach was to cre ...

Tips for utilizing the next link href based on a specific condition

The following code snippet is causing me some trouble: <a onClick={() => { if (fortype === "user") { if (rd.track !== null) { router.push({ pathname: `/tracks/${rd.track._id}`, query: { fr ...

What is the best way to set `:global` as the default in css-modules within next-js?

Currently, I am incorporating CSS modules into a Next.js project. If we take a look at the following code: // foo.module.(s)css .foo :global { animation-name: bounce; // ... } My question is, is there a way to adjust the Webpack configuration in Ne ...

Do not use the .map method! Caution: Every child component in a list must be assigned a unique "key" prop

I have recently started working with NEXT JS and I am encountering a peculiar issue for which I haven't been able to find a solution online. The warning message I'm getting is: "Each child in a list should have a unique key prop." Warning: Each c ...

Issue: Unable to locate the module '/app/apps/landing/server.js'

Objective: Arranging for the launch of an app using a global docker-compose Challenge: The issue lies in starting the app, specifically with this command node ./apps/landing/server.js which fails to locate the server.js file node: internal/modules/cjs/lo ...

Dealing with 404 errors in both server.js and the client side utilizing NextJS and next-routes

I'm in search of a more elegant solution for my next-routes to gracefully handle file not found (specifically route not found) when executing from server.js (server side) and also while operating on the client side with Link. The current solution I ha ...

Experiencing delays when loading more than 200 input fields on the screen due to

So I've been working on a project that involves having potentially unlimited input fields. However, once I add around 200 items, the performance starts to degrade significantly. You can see a demo of this issue here: (To test: Focus on the last input ...

I am encountering difficulties accessing the cPanel URL following deployment on Vercel

Running into some challenges while hosting my Next.js 13 application on cPanel led me to an alternative solution I discovered online. The workaround involved deploying the application on Vercel and adjusting the DNS records in cPanel to direct traffic to ...

Tips for dynamically loading a multitude of icons in Next.js

Is it worth loading these icons dynamically? import { faCheck, faCogs, faCoins, faCouch, faCreditCard, faGhost, faGift, faPuzzlePiece, faQrcode, faTasks, faVideo, faChild, faCubes, } from "@fortawesome/free-solid-svg-icons&qu ...

The query to WpGraphQL results in a null response

I am currently working with a GraphQL query in Nexjs that is connected to headless Wordpress via the WpGraphQl plugin: export const GET_POSTS_BY_CATEGORY_SLUG = gql` query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: In ...

Switching the active className in React and Next.js based on selection status

My goal is to dynamically change the className of each Card component when clicked on. When one Card is selected, the others should revert back to their default className. This is my UserBookingData component: const UserBookingData = ({ bookings }: any) = ...

Tips for resolving the eslint error "An error occurred when attempting to load the rule 'react/display-name': [[GeneratorState]] is not found on 'O'"

My current setup involves using eslint in conjunction with nextjs and eslint-config-next. I prefer to use bun as my package manager, although similar issues have been reported with npm and yarn. I did not introduce any new packages, but after executing bu ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

Are there any alternatives for altering the route and transmitting properties to a different component in Next.js?

Currently, I am located at this specific URL path: http://localhost:3034/dashboard/one. My next step involves passing a substantial object to another component called <Edit/>, which also includes modifying the URL path to become http://localhost:303 ...

Revealing Next.js Environment Variables for Integration with PWA's API System

As per the official documentation of Next.js, exposing an environment variable requires using the NEXT_PUBLIC_ prefix. However, in this case, the admin is utilizing process.env.REACT_APP_API_ENTRYPOINT. In order to access the REACT_APP_API_ENTRYPOINT envi ...