javascript - mongodb 用变量更新数组

标签 javascript arrays mongodb meteor

我有一系列网站,可以对它们进行赞成或反对投票。集合中有一个空数组,用于通过将 userId 插入到数组中来跟踪已投票的用户

问题:我可以插入用户 ID 甚至用户名,但当时它只将 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。这样我就可以检查它是否允许投票。

最佳答案

解决方案:

It seems that the strings only remain if I put "" around them. But I'm using a variable to get the userid/name. When I put "" around it I literally get "theVariable", not helpful.

如果您使用的是 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"}});

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

关于javascript - mongodb 用变量更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35645099/

相关文章:

c - 数组作为函数参数

java - 如何将File[]数组内容添加到ArrayList中?

node.js - 如何 "Fake"测试 Mongoose 模型的日期/时间

javascript - 比较两个字符串时 localeCompare 行为异常

javascript - ECMAScript 5 'use strict' 字符串成本存在哪些?

arrays - 矩阵中基于向量的消除零点

mongodb - Mongo 聚合匹配多个值

java - 通过在一个集合中进行更改来反射(reflect)多个 mongodb 集合中的更改

javascript - 使用 JS 调整 jquery UI 对话框的大小?

javascript - Flask + Ajax 集成 : AttributeError: 'WSGIRequestHandler' object has no attribute 'environ'