【发布时间】:2019-10-15 06:57:49
【问题描述】:
如何让这个查询使用我的变量而不是硬编码的 0?
let pos = 0;
{$set: {'answers.0.acknowledged': data}}
【问题讨论】:
标签: javascript arrays mongodb mongoose
如何让这个查询使用我的变量而不是硬编码的 0?
let pos = 0;
{$set: {'answers.0.acknowledged': data}}
【问题讨论】:
标签: javascript arrays mongodb mongoose
通常您的选择是template literals、Array.join、String.concat 等:
let pos = 0;
let data = 'data';
let query = {$set: {[['answers.', pos,'.acknowledged'].join('')]: data}}
console.log(query);
let pos = 0;
let data = 'data';
let query = {$set: {['answers.'.concat(pos,'.acknowledged')]: data}}
console.log(query);
Array.join、String.concat 有更好的浏览器支持,其中template literals do not。如果要在@客户端使用它们。在您的情况下,如果您在后端使用它们,您可能没有什么可担心的。
【讨论】:
您可以使用 ES6 String Interpolation 和 Computed Property Names 为 $set 构建密钥:
let pos = 0;
let data = 'some data';
let q = {$set: {[`answers.${pos}.acknowledged`]: data}}
console.log(q);
【讨论】: