无法使用来自 ordersschema 的用户名填充到 usersschema

问题描述

我正在尝试检索用户名以填充订单。我从教程中了解到,它说通过使用带有用户模式链接的订单模式,它可以填充该字段。最后,我在下面收到此错误,而不是获得订单名称。我填充字段的方式不正确还是有其他填充字段的方式?

main.js:1 Uncaught (in promise) TypeError: Cannot read property 'name' of null
    at main.js:1
    at Array.map (<anonymous>)
    at Object.render (main.js:1)
    at async P (main.js:1)

检索订单代码

orderRouter.get(
  '/',isAuth,isAdmin,expressAsyncHandler(async (req,res) => {
    const orders = await Order.find({}).populate('user')
    res.send(orders);
  })
);

订单界面

 <div class="order-list">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>DATE</th>
              <th>TOTAL</th>
              <th>USER</th>
              <th>PAID AT</th>
              <th>DELIVERED AT</th>
              <th class="tr-action">ACTION</th>
            <tr>
          </thead>
          <tbody>
            ${orders
              .map(
                (order) => `
            <tr>
              <td>${order._id}</td>
              <td>${order.createdAt}</td>
              <td>${order.totalPrice}</td>

              // the line with error
              <td>${order.user.name}</td>

              <td>${order.paidAt || 'No'}</td>
              <td>${order.deliveredAt || 'No'}</td>
              <td>
              <button id="${order._id}" class="edit-button">Edit</button>
              <button id="${order._id}" class="delete-button">Delete</button>
              </td>
            </tr>

订单架构

import mongoose from 'mongoose';

const orderSchema = new mongoose.Schema(
  {
    orderItems: [
      {
        name: { type: String,required: true },image: { type: String,price: { type: Number,qty: { type: Number,product: {
          type: mongoose.Schema.Types.ObjectId,ref: 'Product',required: true,},],user: { type: mongoose.Schema.Types.ObjectId,ref: 'User',shipping: {
      address: String,city: String,postalCode: String,country: String,payment: {
      paymentMethod: String,paymentResult: {
        orderID: String,payerID: String,paymentID: String,itemsPrice: Number,taxPrice: Number,shippingPrice: Number,totalPrice: Number,isPaid: { type: Boolean,default: false },paidAt: Date,isDelivered: { type: Boolean,deliveredAt: Date,{
    timestamps: true,}
);
const Order = mongoose.model('Order',orderSchema);
export default Order;

用户架构

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: { type: String,email: { type: String,index: true,unique: true },password: { type: String,isAdmin: { type: Boolean,});
const User = mongoose.model('User',userSchema);
export default User;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)