我尝试动态访问 mongo 数据库中的字段。
目标字段由这一行给出:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
哪里
Session.get('contextLayout')
可以是字符串或集合的 _id(例如 userHomeBackgroundColor 或 56xhPYg8w3Qtv9xPLBackgroundColor)。
我不知道如何访问该值。 我尝试了这段代码:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
var tempStore ={};
tempStore['target']=contextTarget;
var newTarget = tempStore.target;
console.log(newTarget);//return the correct value
var color = customConfiguration.findOne({'author':auth}).newTarget;
console.log(color);//return undefined
这不起作用。我想这是因为 newTarget 变量是一个字符串,因为如果我直接在控制台中写入预期结果,它就可以工作。我该怎么办?
编辑。
就像 BraveKenny 所说:
var color = customConfiguration.findOne({'author':auth})[contextTarget];
事实上,没有必要传递tempStore对象。使用方括号键可以正确发送。我已经尝试过了,但在方括号前加了一个点。 @Michael:对于架构,我没有此集合的架构,因为键名称是动态创建的。 非常感谢。
最佳答案
如果我理解正确的话,最后,您想要获取 customConfiguration
对象的一个变量属性,该属性的名称包含在 newTarget
中。
也许可以尝试这个:
var color = customConfiguration.findOne({'author':auth})[newTarget];
基本上当你输入时:
someObject.toto = 'someValue';
var someAttribute = 'toto';
console.log(someObject.someAttribute); //undefined
console.log(someObject[someAttribute]); // 'someValue'
当使用点表示法调用时,JavaScript 将始终假定 someAttribute
是 someObject
的属性。不是范围内设置的变量。如果您想要包含在字符串变量中的属性 toto
的值(在我的例子中,someAttribute
),您必须将此变量作为索引传递,如下所示:
console.log(someObject[someAttribute]); // 'someValue'
关于javascript - 如何从mongo数据库中的字符串传递动态键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29964554/