简体   繁体   English

流星集合中的数字字段名称

[英]Numeric field names in meteor collection

I need to achieve such collection structure: 我需要实现这样的集合结构:

{
    "_id" : "36JaTS8N9uJDHabaq",
    "pages" : {
        1 : {
            "field1" : "value1",
            "field2" : "value2"
        },
        ...
    }
}

Everything is fine, when I'm doing the following: 当我执行以下操作时,一切都很好:

Collection.insert({
    "pages": {
        1: {
            "field1" : "value1",
            "field2" : "value2"
        }
    }
})

But when I'm trying to use the variable containing the number instead of number itself, like: 但是,当我尝试使用包含数字而不是数字本身的变量时,例如:

var number = 1;
Collection.insert({
    "pages": {
        number: {
            "field1" : "value1",
            "field2" : "value2"
        }
    }
})

I receive not the result I want (there is a variable name where number should be): 我没有收到想要的结果(有一个变量名,数字应该在其中):

{
    "_id" : "SjMotZHrtXviuoyqv",
    "pages" : {
        "number" : {
            "field1" : "value1",
            "field2" : "value2"
        }
    }
}

What is the right way to do what I'm trying to achieve? 什么是我要实现的正确方法?

Thanks in advance! 提前致谢!

You can try something like this : 您可以尝试这样的事情:

var doc={
    pages:{}
};

var number="1";
doc.pages[number]={
    "field1":"value1",
    "field2":"value2"
};

Collection.insert(doc);

You can't use variables as keys in object literals in javascript. 您不能将变量用作javascript中对象文字中的键。 See this answer. 看到这个答案。

var number = 1;
var pages = {};
pages[number] = {f1: 'v1', f2: 'v2'};
Collection.insert({pages: pages});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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