[英]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.在我的节点应用程序中,我有一个 ejs 文件,我在其中将对象数组放入一个循环中,对于每条记录,我都有一个点赞按钮和一个显示点赞数,点击时点赞数应该增加一并显示增加的点赞数价值。
I have used ajax request to increment the likes in database and bring back that response to client side javascript.我已经使用 ajax 请求来增加数据库中的点赞数并将该响应返回到客户端 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.
现在,通过使用 document.queryselector(),我把这个元素放在一个变量中并使用 innerText 属性来更新喜欢,我面临的问题是它只更新第一条记录的值,即使点击喜欢按钮另一条记录它总是只更新第一个。
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:这是我的 ajax 请求:
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;
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.您基本上需要将您的 var 更改为 let,因为 var 在全局 scope 上,一旦循环完成,它的值将相同,这将等于限制。 Whereas let is lexical scope and it's value is not global but binded to each iteration.
而 let 是词汇 scope ,它的值不是全局的,而是绑定到每次迭代。
<% 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.更多 google let vs var 和提升的概念。 That might clear up things for you:)
这可能会为你解决问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.