简体   繁体   中英

How do i reference 1 Mongoose Schema inside another as its property?

I am trying to make a store app and have created two mongoose schemas. Order.js and Product.js, I want to reference the product schema as a property of the order schema.

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 }
);

product.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:

product

with your fields, then create your Product schema by simply const Product = new Schema(product); , then you can import the product object here in your order.js and declare your schema as follows:

import product;
const Order = new Schema({
......
......
order : {
   type : product , 
   ......
}
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM