简体   繁体   中英

How do i update a field for a specific record of a collection in mongodb?

in my node app, i have an ejs file where i am putting array of objects into a loop and for each record i have a like button and a display to show number of likes which on click should increment the likes by one and display the incremented value.

I have used ajax request to increment the likes in database and bring back that response to client side javascript. Now, by using the document.queryselector(), i put this element in a variable and use innerText property to update the likes, The problem i am facing is that it only updates that value for the first record, even if a click like button of another record it always updates the first one only.

here is the code

 <% for(var i=start; i<=limit; i+=1) { %>
           
    <button onclick="like(this)" getpost="<%=posts[i].slug%>" ><li class="btns-blog"><i></i><span class="count" id="likecount" ><%=posts[i].likes%></span></li></button>
    
<% } %> 

this is my ajax request:

function like(e){
        
    if(currentUser){
        var curPostSlug = e.getAttribute('getpost');  
        httpRequest = new XMLHttpRequest();
        if (!httpRequest) {
          alert('Giving up :( Cannot create an XMLHTTP instance');
          return false;
        }
        httpRequest.onreadystatechange = likeRequest;
        httpRequest.open('GET', '/' + curPostSlug);        
        httpRequest.send();
      
      }
  }

  function likeRequest(){
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          var respJson = JSON.parse(httpRequest.responseText)
          console.log(respJson)
          document.querySelector('.count').innerText = respJson.updatedlikes;
        } else {
          alert('There was a problem with the request.');
        }
      }
    }

I want this

document.querySelector('.count').innerText = respJson.updatedlikes;

line to work for a specific iteration, currently it always updates for first record on the page. How can i acheive this?

You basically need to change your var to let, because var is on the global scope and it's value will be same once the loop is completed which will be equal to limit. Whereas let is lexical scope and it's value is not global but binded to each iteration.

<% for(let i=start; i<=limit; i+=1) { %>
           
    <button onclick="like(this)" getpost="<%=posts[i].slug%>" ><li class="btns-blog"><i></i><span class="count" id="likecount" ><%=posts[i].likes%></span></li></button>
    
<% } %> 

For more google let vs var and concept of hoisting. That might clear up things for you:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM