You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Mongoose与Express.js中获取当前登录用户关联订单返回空数组的问题

问题:获取当前登录用户专属订单始终返回空数组

我有两个Mongoose模型——Order和User,二者为一对多关系,数据库中已存储不同用户创建的订单,但编写的控制器获取当前登录用户的订单时,始终返回空数组。

user.model.js

import mongoose from "mongoose";

const userSchema = mongoose.Schema(
  {
    firstname: {
      type: String,
      required: [true, "Name is required"],
    },
    lastname: {
      type: String,
      required: [true, "LastName is required"],
    },
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true,
    },
    password: {
      type: String,
      required: [true, "Password is required"],
    },

    isAdmin: { type: Boolean, default: false },
  },
  {
    timestamps: true,
  }
);

const User = mongoose.model("User", userSchema);
export default User;

order.model.js

import mongoose from "mongoose";

const orderSchema = mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
    customerId: { type: String },
    paymentIntentId: { type: String },
    products: [
      {
        id: { type: String },
        name: { type: String },
        category: { type: String },
        price: { type: String },
        size: { type: String },
        color: { type: String },
        thumbnail: { type: String },
        qty: { type: Number },
      },
    ],
    // subTotal: { type: Number, required: true },
    total: { type: Number, required: true },
    shipping: { type: Object, required: true },
    deliveryStatus: { type: String, default: "pending" },
    paymentStatus: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

const Order = mongoose.model("Order", orderSchema);

export default Order;

order.controller.js

export const getAllOrders = async (req, res) => {
  const { _id } = req.user;

  // console.log(typeof id);

  try {
    const orders = await Order.find({userId: _id});

    console.log(orders);
    res.status(200).json({ orders });
  } catch (error) {
    res.status(500).json({ msg: error.message });
  }
};

排查与解决步骤

  1. 验证req.user._id的类型匹配
    数据库中Order的userId是ObjectId类型,如果req.user._id是字符串,需要转换为ObjectId才能匹配:

    import mongoose from 'mongoose';
    // ...
    const orders = await Order.find({ userId: mongoose.Types.ObjectId(_id) });
    

    先打印typeof _id和_id的值,确认类型是否为字符串。

  2. 确认req.user是否正确挂载
    在控制器中打印req.user,检查_id字段是否存在且是当前登录用户的正确ID,有可能登录中间件未正确将用户信息挂载到req.user上。

  3. 核对数据库中的订单数据
    直接通过MongoDB客户端(如Compass)查询,确认目标用户的_id与订单的userId字段完全一致,排除拼写错误或类型不匹配的情况。

  4. 优化查询便于排查
    使用lean()返回普通JavaScript对象,避免Mongoose文档对象的包装干扰排查:

    const orders = await Order.find({ userId: _id }).lean();
    

内容的提问来源于stack exchange,提问作者user3869304

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:15:19