I have been trying to use one schema in another schema. I have a product schema with details about the product and cart schema which includes details about the product and cart details.
When I click on 'Add to cart' my cart needs to have details about the product and qty. As I need my product details in my cart I have to refer to those details in my cart. I am not sure how to do it.
Can anyone please help me?
Product.js
const ProductSchema=new mongoose.Schema({
name:{
type:String,
required:true,
minlength:1,
trim:true
},
price:{
type:Number,
required:true,
},
description:{
type:String,
required:true,
trim:true
},
ingredients:{
type:String,
required:true,
trim:true
},
usage:{
type:String,
required:true,
trim:true
},
imageURL:{
type:String,
required:true
}
})
cart.js
const mongoose=require('mongoose');
const Product=require('./product');
const CartSchema=new mongoose.Schema({
product:{
type:mongoose.Schema.Types.ObjectId,
ref:'Product',
},
qty:{
type:Number,
default:1
}
})
const Cart=mongoose.model('Cart',CartSchema);
module.exports=Cart;
app.js
app.post('/cart',(req,res)=>{
console.log(product);
let newCart=new Cart({
product:Product.findOne({}),
qty:req.body.qty
});
newCart.save().then((items)=>{
res.send(items);
})
})
I am not sure how to get the data of my product inside the cart.