TypeError: 在 Next.js 和 Mongoose 应用程序中无法读取 null(读取 ‘get’)的属性。

huangapple go评论88阅读模式
英文:

TypeError: Cannot read properties of null (reading 'get') in Next.js and Mongoose application

问题

我正在使用 nextjsmongoose 和一个在 cookie 中使用的 jwt 令牌制作电子商务应用程序。

我遇到以下错误:TypeError: Cannot read properties of null (reading 'get')

models/order.js:

import {model, models, Schema} from "mongoose";
import mongoose from 'mongoose';

const OrderSchema = new mongoose.Schema({
  products: {
    type: Object,
    required: true,
  },
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  address: {
    type: String,
    required: true,
  },
  city: {
    type: String,
    required: true,
  },
  paid: {
    type: Number,
    default: 0
  },
}, {timestamps: true});

const Order = models?.Order || model('Order', OrderSchema)

export default Order;

这个错误发生在我想要访问我的订单页面 (pages/orders.js) 时:

import { useEffect, useState } from "react";
import axios from "axios";
import jwt from "jsonwebtoken";
import cookie from "cookie";
import Order from "../models/Order";

function Orders() {
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    async function fetchOrders() {
      const res = await axios.get("/api/secret");
      const secret = res.data.secret;
      // 从 cookie 中获取 JWT 令牌
      const token = cookie.parse(document.cookie).OursiteJWT;
      const decoded = jwt.verify(token, secret);
      const userId = decoded._id
      console.log(userId)
      // 从后端 API 获取用户的订单
      const response = await axios.get(`/api/orders?user_id=${userId}`);
      const orders = response.data;

      setOrders(orders);
    }

    fetchOrders();
  }, []);

  return (
    <div>
      {orders.map((order) => (
        <div key={order._id}>
          <h2>Commande {order._id}</h2>
          <p>Utilisateur: {order.name}</p>
          <p>Adresse: {order.address}</p>
          <p>Ville: {order.city}</p>
          <p>Produits:</p>
          <ul>
            {order.products.map((product) => (
              <li key={product._id}>{product.name}</li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}

export default Orders;

我注意到我不能在我的 useEffect 中或者在我的 useEffect 中的 API 调用中放置 console.log,因为我的 useEffect 甚至不运行,问题来自于我的模型。如果我删除我的 useEffect,我仍然会遇到相同的错误,所以问题并不是来自于我的 useEffect。

英文:

I'm making an ecommerce application with nextjs and mongoose and a jwt token in a cookie.

I have the following error : TypeError: Cannot read properties of null (reading &#39;get&#39;)
TypeError: 在 Next.js 和 Mongoose 应用程序中无法读取 null(读取 ‘get’)的属性。

models/order.js :

import {model, models, Schema} from &quot;mongoose&quot;;
import mongoose from &#39;mongoose&#39;;

const OrderSchema = new mongoose.Schema({
  products: {
    type: Object,
    required: true,
  },
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: &quot;User&quot;,
  },
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  address: {
    type: String,
    required: true,
  },
  city: {
    type: String,
    required: true,
  },
  paid: {
    type: Number,
    default: 0
  },
}, {timestamps: true});

const Order = models?.Order || model(&#39;Order&#39;, OrderSchema)

export default Order;

This error comes when I want to access my orders page (pages/orders.js) :

import { useEffect, useState } from &quot;react&quot;;
import axios from &quot;axios&quot;;
import jwt from &quot;jsonwebtoken&quot;;
import cookie from &quot;cookie&quot;;
import Order from &quot;../models/Order&quot;;

function Orders() {
  const [orders, setOrders] = useState([]);
  

  useEffect(() =&gt; {
    async function fetchOrders() {
      const res = await axios.get(&quot;/api/secret&quot;);
      const secret = res.data.secret;
      // Get the JWT token from the cookies
      const token = cookie.parse(document.cookie).OursiteJWT;
      const decoded = jwt.verify(token, secret);
      const userId = decoded._id
      console.log(userId)
      // Fetch the orders for the user from the backend API
      const response = await axios.get(`/api/orders?user_id=${userId}`);
      const orders = response.data;

      setOrders(orders);
    }

    fetchOrders();
  }, []);

  return (
    &lt;div&gt;
      {orders.map((order) =&gt; (
        &lt;div key={order._id}&gt;
          &lt;h2&gt;Commande {order._id}&lt;/h2&gt;
          &lt;p&gt;Utilisateur: {order.name}&lt;/p&gt;
          &lt;p&gt;Adresse: {order.address}&lt;/p&gt;
          &lt;p&gt;Ville: {order.city}&lt;/p&gt;
          &lt;p&gt;Produits:&lt;/p&gt;
          &lt;ul&gt;
            {order.products.map((product) =&gt; (
              &lt;li key={product._id}&gt;{product.name}&lt;/li&gt;
            ))}
          &lt;/ul&gt;
        &lt;/div&gt;
      ))}
    &lt;/div&gt;
  );
}

export default Orders;

I noticed that I can't put console.log in my useffect or in api calls that are in my useffect because my useffect doesn't even run because the problem comes from my model.
If I delete my useffect I still have the same error so the problem does not come from my useffect.

答案1

得分: 1

mongoose 是服务器端的包。你不能在客户端组件中使用 Order 模型。你可以在服务器端代码中使用模型,包括在 API 函数或 getServerSide 函数中。

英文:

mongoose is server-side package. you cannot use the Order model inside client components. You can use models with server-side code, inside api functions or getServerSide functions.

huangapple
  • 本文由 发表于 2023年1月8日 22:00:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定