How to include one schema as a type in another schema and post the data in mongoose

Viewed 608

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.

1 Answers

products:[{ type:mongoose.Schema.Types.ObjectId, ref:'Product', }],

First of all, you chan change here with square brackets if you want to save more than one products inside card schema.

In app.js file, firstly find product and assign to a variable

const _product = await Product.findOne({})

Secondly, You should get the '_id' field of the product variable. Because in Cart Schema your product field's type is mongoose.Schema.Types.ObjectId so product's object id.

However in your case:

const newcart = new Cart({product: _product._id , qty:req.body.qty})
newcart.save()

Answer to Comment:

const CartSchema = new Mongoose.Schema(
{
        products: [
    {
    _id:false,
    id: {type: Schema.Types.ObjectId, ref:'Product'},
    }
],
qty:{
    type:Number,
    default:1
}}, {versionKey: false})



app.post('/cart', async (req,res)=>{

//Find product with Ball name and wait for mongoose to complete findOne task

const product = await Product.findOne({name:"Ball"})

const newCart=new Cart();
newCart.qty = 123

//In new cart schema products is an array which include product _id with type of object id. So When i find product with name 'Ball' im pushing _id of Ball product in to my newCart's products array

newCart.products.push(product._id)

//then im saving my edited cart
const savedNewCart = await newCart.save()

//Send response for saved card
res.send(savedNewCart) })



    
Related