二级嵌套架构不填充

问题描述

抱歉分享太长的代码。我只是认为它会澄清事情。我有两种拉取订单的方法。 (1) 源于 Order 模式。 (2) 从 User 模式中生根

我想专注于拉订单的第二种方式。我正在尝试像这样填充我的 User.find 查询用户 > 订单 > 产品

enter image description here

但这就是我在邮递员测试中得到的全部内容。产品字段不会填充到我选择的字段。

enter image description here

// User.js
const mongoose = require("mongoose");


const userSchema = new mongoose.Schema({
  email: {
    type: String,required: [true,"Email is required"]
  },password: {
    type: String,"Password is required"]
  },isAdmin: {
    type: Boolean,default: false
  },orders: [
    {
      order: {
        type: mongoose.Schema.Types.ObjectId,ref: 'Order'
      },_id: false
      
    }
  ]
});

module.exports = mongoose.model("User",userSchema);
// Order.js
const mongoose = require("mongoose");

const orderSchema = new mongoose.Schema({
  totalAmount: {
    type: Number,"Total amount is required"]
  },purchasedOn: {
    type: Date,default: new Date()
  },buyer: {
    type: mongoose.Schema.Types.ObjectId,ref: 'User'
  },products: [
    {
      product: {
        type: mongoose.Schema.Types.ObjectId,ref: 'Product',required: true
      },quantity: {
        type: Number,"Product quantity is required."],min: [1,"Minimum product quantity is 1."]
      },purchasePrice: {
        type: Number,min: [0,"Price cannot be negative."]
      },_id: false
    }
  ]
});


module.exports = mongoose.model("Order",orderSchema);
// Product.js
const mongoose = require("mongoose");


const productSchema = new mongoose.Schema({
  name: {
    type: String,"Product name is required"]
  },sku: {
    type: String,"Product SKU is required."]
  },description: {
    type: String,"Product description is required"]
  },price: {
    type: Number,"Product price is required"]
  },isActive: {
    type: Boolean,default: true
  },createdOn: {
    type: Date,_id: false
    }
  ]
});

module.exports = mongoose.model( "Product",productSchema );

解决方法

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

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

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