node.js - 产品参考是不安全的
问题描述
我有一个名为 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 行定义
我是否需要在此导入产品模型,如果是,那么我该怎么做,如果不是,那么错误在哪里
解决方案
为了在您的 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 };
推荐阅读
- c - 使用 FatFs 访问 SDHC 卡上的现有分区
- vba - How to execute an external .sql file pass-through query in ms-access
- java - 如何在地图输出中写入两个键和一个值?
- python - 基于规则的词性解析困境
- java - 如何使用 Java 程序在记事本中关闭文本文件
- python - 从python中的列表中减法
- python - 没有循环的条件语句
- java - IText 是否支持 PAdES 签名承诺类型?
- python - 从pdf图像文件中提取文本
- kubernetes - istio-sidecar-injector kube configmap 中缺少值