如何在一个模型中接收另一个模型的数组?(mongoose)(mongoDB)

yvfmudvl  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(149)

我有一个订单模型/模式,我的目标是在“list”中的这个模型中,我以数组格式接收来自模型Cart的信息。我如何使用ref做到这一点呢?
推车模型

const mongoose = require('mongoose');

const CartSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        note: {
            type: String,
            required: true,
        },
        price: {
            type: Number,
            required: false,
        },
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Cart", CartSchema);

订货

const mongoose = require('mongoose');

const OrderSchema = new mongoose.Schema(
    {
        list: {
            name: String,
            notes: String,
        },
        totalAmount: {
            type: Number,
            required: true,
        },
        payment: {
            type: String,
            required: true,
        },
        address: {
            type: String,
            required: true,
        },
        addressNote: {
            type: String,
            required: false,
        },
        createdAt: {
            type: Date,
            default: Date.now,
        }
    },
    { timestamps: true }
  );
  
module.exports = mongoose.model("Order", OrderSchema);

基本上以数组格式接收“列表”中按型号顺序排列的型号推车信息

bzzcjhmw

bzzcjhmw1#

您应该将您的list定义为ObjectId数组,引用Cart模型:

const OrderSchema = new mongoose.Schema(
  {
      list: [{
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Cart'
      }],
      ...
  });

然后,要检索list中的值,只需填充Order

Order.find({}).populate('list').exec();

相关问题