Home > other >  backend shop. Showing certain products
backend shop. Showing certain products

Time:08-18

I'm new to backend and I'm confused about how shops load (for example) 20 products, then when you click onto the next page you get 20 more new products.. I'm using nodejs with mongoose and ejs, so if anyone could submit an example with explanation I would really appriciate it! But an explanation only would also work! Thank's in advance! (I don't really know how to google the answer for this question, so that's why I'm here!)

CodePudding user response:

Basically you need to store the product details in a collection first . You can accomplish this by adding a form on the admin route . To store the image if you are using express you can use a middleware called express-fileupload then in your app.js file var fileupload = require("express-fileupload"); then you can register the middleware by app.use(fileupload()); in your app.js file

To save the image here i am storing the image in server itself but this is not recommended . You want to rename the image with a connection . for eg the mongo document inserted id . This will really help you to loop products easily i will show you an example on how to add the data from form to db and store the image with the mongo id.

router.post('/add-products', (req, res) => {
let datainsert = req.body,
db.get().collection('products').insertOne(datainsert).then((data) => {
    let id = data.insertedId
    let image = req.files.image
    image.mv('./public/images/product-images/'   id   '.jpg', (err) => {
        if (!err) {
           console.log("document added and image saved)
            res.redirect('/')
        } else {
            console.log("err"   err);
        }
    })
})

Now your product will be added to db and the image will be stored in server . To view the products you can basically loop through the documents

hope it helped you if you face any errors or doubts feel free to reply . Thanks !

CodePudding user response:

I just figured it out. i can hide all products, then store them in an array and use this code to only show 5 new products in the list every timethe query parameter "page" goes up. Heres the code: (its a bit janky but it does the job, and it might help someone who's looking for the same answer as me! Happy coding!

  function getQueryVariable(variable) {
    let query = window.location.search.substring(1);
    let pageNum = query.split("=")[1];
    return pageNum * 5;
  }
  let pageNum = getQueryVariable("page");

  let namn = [];
  let namnAttSamla = document.getElementsByClassName("namn");
  for (let i = 0; i < namnAttSamla.length; i  ) {
    namn.push(namnAttSamla[i].innerText);
  }

  for (let i = pageNum  ; i < pageNum   4; i  ) {
    console.log(namnAttSamla[i].innerText, "index:", i);
  }
  • Related