首页 > 解决方案 > 产品参考是不安全的

问题描述

我有一个名为 order 的模型。订单模型有一个字段名称产品,它是对产品模型的引用。我的订单模型就像

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
const ProductCartSchema = new Schema({
  product: {
    type: ObjectId,
    ref: Product,
  },
  name: String,
  count: Number,
  price: Number,
});

const orderSchema = new Schema(
  {
    products: [ProductCartSchema],
    transaction_id: {},
    amount: { type: Number },
    address: { type: String },
    updated: Date,
    user: {
      type: ObjectId,
      ref: User,
    },
  },
  { timestamps: true }
);

var Order = mongoose.model('Order', orderSchema);
var ProductCart = mongoose.model('ProductCart', ProductCartSchema);

module.exports = { Order, ProductCart };

我的产品模型架构就像

    var mongoose = require(mongoose);
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
const productSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
      maxlength: 32,
      trim: true,
    },
    description: {
      type: String,
      required: true,
      maxlength: 2000,
      trim: true,
    },
    price: {
      type: Number,
      required: true,
      maxlength: 32,
      trim: true,
    },
    category: {
      type: ObjectId,
      ref: 'Category',
      required: true,
    },
    stock: {
      type: Number,
    },
    sold: {
      type: Number,
      default: 0,
    },
    photo: {
      type: Buffer,
      contentType: String,
    },
  },
  { timestamps: true }
);
module.exports = mongoose.model('Product', productSchema);

它给了我错误

产品未在 order.js 第 7 行定义

我是否需要在此导入产品模型,如果是,那么我该怎么做,如果不是,那么错误在哪里

标签: node.jsmongooseschema

解决方案


为了在您的 Order.js 架构中使用产品引用,您需要导入它。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema;
var Product = require('Product'); <----------------------------------- Import this
const ProductCartSchema = new Schema({
  product: {
    type: ObjectId,
    ref: Product,
  },
  name: String,
  count: Number,
  price: Number,
});

const orderSchema = new Schema(
  {
    products: [ProductCartSchema],
    transaction_id: {},
    amount: { type: Number },
    address: { type: String },
    updated: Date,
    user: {
      type: ObjectId,
      ref: User,
    },
  },
  { timestamps: true }
);

var Order = mongoose.model('Order', orderSchema);
var ProductCart = mongoose.model('ProductCart', ProductCartSchema);

module.exports = { Order, ProductCart };

推荐阅读