Home > Back-end >  do foreach 5 times
do foreach 5 times

Time:10-24

i have my project with nodejs en mongoose. i want to get only the 5 first items of the database. as you see in the code below i get all the itemssmall. but i only want the get the first 5 items small on the site. how do i do that with a for loop.

          <% itemsSmall.forEach(function(itemsSmall) { %>
            <%if(String(image._id) === String(itemsSmall.imageId)){%>
              <div >
              <p ><strong><%= itemsSmall.title %>:</strong> <%=itemsSmall.smallInformation %></p>
            
              <div >
                <% if(image.userId == user.userId || user.admin > 2){ %>
                <form action="/view/deleteSmall/<%= itemsSmall._id %>?_method=delete" method="POST">
                  <textarea name="imageId" id="imageId" hidden><%= image._id %></textarea>
                  <button  type="submit">delete</button>
                </form>
                <%}%>
              </div>
              </div>
          <%}%>           
          <% }) %> 
        </div>

CodePudding user response:

@NeNad this is the backend

router.get("/:id", (req, res) => {
  const id = req.params.id;
  //find the 3 models (images and information)
  Image.findById(id)
    .then((result) => {
      itemsBig.find().sort({ CreatedAt: -1 }).then((itemsBig) => {
          itemsSmall.find().sort({ CreatedAt: -1 }).then((itemsSmall) => {
              //render picturedetail and send all this information with
              res.render("pictureDetail", {
                itemsSmall: itemsSmall,
                itemsBig: itemsBig,
                image: result,
                picture: id,
                user: req.auth,
                title: "Details",
              });
            }).catch((err) => {console.log(err); });
        }).catch((err) => { console.log(err);});
    }).catch((err) => {console.log(err);});
});

//create the big information blocks
router.post("/uploadBig", (req, res) => {
  const id = req.params.id; //set the id from the page
  //create the image
  itemsBig
    .findById(id)
    .then((result) => {
      //set the image in een obj
      var obj = {
        title: req.body.Title,
        bigInformation: req.body.bigInformationText,
        userId: req.auth.userId,
        imageId: req.body.imageId,
      };
      //all the thing of the obj set to the model
      itemsBig.create(obj, (err, items) => {
        if (err) {
          console.log(err);
        } else {
          //upload the model
          items.save();
          res.redirect("/view/"   req.body.imageId);
        }
      });
    })
    .catch((err) => {
      console.log(err);
    });
});

CodePudding user response:

You can limit the number of items returned from the backend. You can use limit() method for it:

itemsSmall.find().sort({ CreatedAt: -1 }).limit(5).then((itemsSmall) => {
  • Related