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 '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;
This error comes when I want to access my orders page (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;
// 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 (
<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;
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.
CodePudding user response:
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.