[英]How to best reference another schema in a Mongoose schema property?
[英]How do i reference 1 Mongoose Schema inside another as its property?
我正在尝试制作一个商店应用程序并创建了两个 mongoose 模式。 Order.js 和 Product.js,我想将产品模式引用为订单模式的属性。
Order.js
const mongoose = require('mongoose');
const Product=require('../models/product.js');
const orderSchema = new mongoose.Schema(
{
date: {
type:Date,
default: Date.now},
customerName: String,
customerAddress: String,
creditCard: Number,
products:[] //product model
},
{ timestamps: true }
);
产品.js
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema(
{
name: String,
price: Number,
category: String
},
{ timestamps: true }
);
const Product = mongoose.model('Product', productSchema);
module.exports= Product;
This is my approach when it comes to nested schemas in mongoose: first you have to create an object of your Product schema, to avoid duplicating your Product model, you can create an object:
产品
使用您的字段,然后通过简单地创建您的产品架构const Product = new Schema(product);
,然后您可以在 order.js 中在此处导入产品 object 并声明您的架构如下:
import product;
const Order = new Schema({
......
......
order : {
type : product ,
......
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.