我收集了一些网站,可以对它们进行上下投票。集合中有一个空数组,可通过将userId插入到该数组中来跟踪已投票的用户

问题:我可以插入userID或什至用户名,但是那时候它仅将id / name变量存储为字符串。如果我再次单击以投票,则上一个元素将变为整数。似乎只有在我在字符串前后加上“”时,字符串才会保留。但是我正在使用一个变量来获取用户名/名称。当我在其周围加上“”时,我实际上会得到“ theVariable”,没有帮助。我已经尽力了....任何帮助,我们都感激不尽。

图式

{
                url:url,
                title:title,
                description:description,
                createdOn:new Date(),
                createdBy:Meteor.user()._id,
                votes: 0,
                upVotes: 0,
                downVotes: 0,
                voted: []
                }




"click .js-downvote":function(event){
        // access the id for the website in the database

        var website_id = this._id;
        console.log("Down voting website with id "+website_id);

        //add a  down vote
        var user = Meteor.user()._id;
        if (user){
            var theUser = this.voted.push(user);
            Websites.update({_id:website_id}, {$inc: {votes: 1}}, {$inc:{downVotes: -1 }}, {$push:{voted: theUser}});
            }
           console.log(this.voted);
        return false;// prevent the button from reloading the page
    }


每次单击时,都会在控制台获得输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "mWe4r2JcfhRAvn97y"]


首先,我得到了字符串,然后在每次单击时,字符串向下移动,第一个元素变为数字。我需要每次存储用户ID。因此,我可以核对是否允许投票。

最佳答案

解决方案:


  似乎只有在我在字符串前后加上“”时,字符串才会保留。但
  我正在使用一个变量来获取用户名/名称。当我在它周围加上“”时
  我从字面上得到“ theVariable”,没有帮助。


如果您使用的是ES6或更高版本的JS,则可以使用字符串插值。您必须使用反引号(`)而不是单引号(')。

例:

var name = "Rose";
console.log(`"My name is ${name}"`);


输出:

"My name is Rose"


在您的代码中执行以下操作:

 Websites.update({_id:website_id}, {$push:{voted: `"${theUser}"`}});


它被插值到:

Websites.update({_id:website_id}, {$push:{voted: "userid within quotes"}});


您将获得报价。使用此方法替换查询

10-07 19:28
查看更多