【问题标题】:Get position with variable and then modify specific object in mongodb使用变量获取位置,然后修改 mongodb 中的特定对象
【发布时间】:2019-10-15 06:57:49
【问题描述】:

如何让这个查询使用我的变量而不是硬编码的 0?

let pos = 0;

{$set: {'answers.0.acknowledged': data}}

【问题讨论】:

    标签: javascript arrays mongodb mongoose


    【解决方案1】:

    通常您的选择是template literals、Array.join、String.concat 等:

    let pos = 0;
    let data = 'data';
    
    let query = {$set: {[['answers.', pos,'.acknowledged'].join('')]: data}}
    
    console.log(query);

    String.concat:

    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。如果要在@客户端使用它们。在您的情况下,如果您在后端使用它们,您可能没有什么可担心的。

    【讨论】:

      【解决方案2】:

      您可以使用 ES6 String Interpolation 和 Computed Property Names 为 $set 构建密钥:

      let pos = 0;
      let data = 'some data';
      let q = {$set: {[`answers.${pos}.acknowledged`]: data}}
      console.log(q);

      【讨论】:

        猜你喜欢
        • 2016-08-17
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-12
        • 1970-01-01
        相关资源
        最近更新 更多