0
votes

I have 2 Schemas. Shop and Product. One shop can have many products. But I also have more than one Shop. Let's say I have 5 shops, and each of those shops have their own products. I am able to save the products and find their IDs in the Shops respectively. But I am struggling to output products that belong to one specific shop. I can output each shop by their ID and see all the product IDs added. But how do I get the product name, description etc (all Product fields) of each product in a shop?

My project works like this: I create a shop, then I add products to each shop by selecting the shop's ID and storing the product ID inside the shop. Then in my view I want to eventually be able to select a shop and show all the products inside the shop.

I am stuck on getting the rest of the fields for Products! I have read through the documentation. Maybe I am missing something? Please help.

My Product model

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    shopName: {
        type: String,
    },
    product: {
        type: String,
        required: true
    },
    productDescription: {
        type: String,
        required: true,
    },
    productPrice: {
        type: Number,
        required: true
    },
    inStock: {
        type: Boolean,
        required: true
    },
    totalStock: {
        type: Number,
        required: true
    },
    productImage: {
        type: Object,
        required: true,
        data: Buffer, 
        contentType: String
    }
});

const Product = mongoose.model('Product', ProductSchema);
module.exports = Product;

My Shop Model:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ShopSchema = new Schema({
    shopName: {
        type: String,
        required: true
    },
    shopImage: {
        type: Object,
        required: true,
        data: Buffer, 
        contentType: String 
    },
    shopDescription: {
        type: String,
        required: true
    },
    shopCategory: {
        type: String,
        required: true
    },
    products: [{
        type: Schema.Types.ObjectId,
        ref: 'productModel'
    }]
}, { timestamps:true });

const Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;

My routes:

//get all shops
//WORKS
router.get('/shops', (req, res) => {
    model.Shop.find()
        .then(result => res.render('shop/shops', { title: 'Shops', shops: result }))
        .catch(err => console.log(err));
});

//get all products
// HOW TO GET THE PRODUCT NAME, PRICE, DESCR ETC??
router.get('/products/:id', (req, res) => {
    model.Product.find()
        .then(result => res.render('shop/products', { title: 'Products View', products: result }))
        .catch(err => console.log(err));
});

// Route for retrieving a Shop by id and populating it's Product.
// Returns the shop with the product ids, but how to get the product fields???
router.get('/shops/:id', (req, res) => {
    model.Shop.findOne({ _id: req.params.id })
        .populate("product", 'product')
        .then(result => {
            return res.json(result)
        })
        .catch(err => console.log(err));
});

// Route for creating a new Shop
//WORKS
router.post('/add-shop', upload.single('shopImage'), (req, res) => {
    const shop = new model.Shop({
        shopName: req.body.shopName,
        shopCategory: req.body.shopCategory,
        shopDescription: req.body.shopDescription,
        shopImage: req.file
    });
    shop.save()
        .then(result => res.redirect('/shops'))
        .catch(err => console.log(err));
});

// Route for creating a new product and updating Shop "productName" field with it
//WORKS
router.post('/shop/:id', upload.single('productImage'), (req, res) => {
    const id = req.params.id;
    const product = new model.Product({
        product: req.body.product,
        productDescription: req.body.productDescription,
        productPrice: req.body.productPrice,
        inStock: req.body.inStock,
        totalStock: req.body.totalStock,
        productImage: req.file
    })
    product.save()
        .then(productModel => {
        return model.Shop.findOneAndUpdate({ _id: req.params.id }, {$push: {products: productModel._id}}, {new: true})
    })
    .then(result => res.redirect('/products/' + id))
    .catch(err => console.log(err));
});

//get products add page
//WORKS
router.get('/add-product', (req, res) => {
    model.Shop.find()
        .then(result => res.render('shop/add-product', { title: 'Add Product', shops: result, id: result._id }))
        .catch(err => console.log(err));
});

JSON output from one shop. The products only display IDs. Is that right? I am new to this.

{
    "products": [
        "5f01c81db57d61236ddefb95",
        "5f01c878b57d61236ddefb96",
        "5f01cd9735fee92874b446b2",
        "5f01ceddf803982924ecb165"
    ],
    "_id": "5f006113fe371c497fe4d5f6",
    "shopName": "Makro",
    "shopCategory": "Retail",
    "shopDescription": "A massive retail shop",
    "shopImage": {
        "fieldname": "shopImage",
        "originalname": "makro.png",
        "encoding": "7bit",
        "mimetype": "image/png",
        "destination": "public/images/uploads/shop-images",
        "filename": "19ba3c0396f8dfaa63aceaaad24e919f",
        "path": "public/images/uploads/shop-images/19ba3c0396f8dfaa63aceaaad24e919f",
        "size": 97140
    },
    "createdAt": "2020-07-04T10:59:31.705Z",
    "updatedAt": "2020-07-05T13:00:13.802Z",
    "__v": 0
}
1

1 Answers

0
votes

pass only product, so it's going to give all details: like this

router.get('/shops/:id', (req, res) => {
    model.Shop.findOne({ _id: req.params.id })
        .populate('product')
        .then(result => {
            return res.json(result)
        })
        .catch(err => console.log(err));
});

To get product details everything is in result. You can use like-

result.productPrice ...