mongodb 为什么我得到一个错误当我尝试到使用我的模型?

li9yvcax  于 2023-01-08  发布在  Go
关注(0)|答案(2)|浏览(135)

我正在用Mongoose开发一个NextJS应用程序。
当我尝试使用Mongoose的模型时,我得到了一个"Cannot read properties of null (reading 'get')"错误。
以下是错误的屏幕截图:

我已经检查了我是否正确地导入了我的模型,并且正确地初始化了Mongoose,但是我找不到这个错误的原因。
型号/订单. 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;

型号/用户.js:

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

const UserSchema = new Schema( {
  email:{
    type:String,
    required:true,
    unique:true,
  },
  password:{
    type:String,
    required:true,
  }
});

const User = typeof models === 'object' ? models.User : model('User', UserSchema);

export default User ;

和前面我调用我的数据在nextjs页面/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
      // Fetch the orders for the user from the backend API
      const response = await axios.get(`/api/orders?user_id=${userId}`);
      const orders = response.data;

      // Populate the user_id field in each order with the associated user object
      const populatedOrders = await Promise.all(orders.map(async (order) => {
        return await Order.findById(order._id).populate("user_id");
      }));

      setOrders(populatedOrders);
    }

    fetchOrders();
  }, []);

  return (
    <div>
      {orders.map((order) => (
        <div key={order._id}>
          <h2>Commande {order._id}</h2>
          <p>Utilisateur: {order.user_id.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;

API/订单:

/* eslint-disable import/no-anonymous-default-export */
import Order from "../../models/Order";
import {initMongoose} from "../../lib/mongoose";

initMongoose()

export default async function(req, res) {
  // Get the user ID from the query string
  const userId = req.query.user_id;

  // Find the orders for the user
  const orders = await Order.find({ user_id: userId }).populate("user_id");

  // Send the orders as the response
  res.json(orders);
};

API/密码:

export default async function handler(req, res) {
  const { method } = req;

  if (method === 'GET') {
    res.json({ secret: process.env.SECRET });
  } else {
    res.setHeader('Allow', ['GET']);
    res.status(405).end(`Method ${method} Not Allowed`);
  }
}
w8biq8rn

w8biq8rn1#

订单架构应为-

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});
mwyxok5s

mwyxok5s2#

您正在尝试在Next.js路由处理程序中创建快速路由处理程序。将api/secret中的代码重构为:

export default async function handler(req, res) {
  res.json({ secret: process.env.SECRET })
}

如果您还希望此路由遵循REST协议并且只允许接受GET请求,则可以使用以下命令:

export default async function handler(req, res) {
  const { method } = req;

  if (method === 'GET') {
    res.json({ secret: process.env.SECRET });
  } else {
    res.setHeader('Allow', ['GET']);
    res.status(405).end(`Method ${method} Not Allowed`);
  }
}

相关问题