【问题标题】:Update value with mongoose用猫鼬更新值
【发布时间】:2019-01-23 13:20:59
【问题描述】:

我想在 mongoose 中更新一个值,该值在两个数组中,所以它不起作用。

这是我使用 console.log 访问值的方式。

console.log('MyValue',bestClustering.cluster_importance[0].feature_importance[0].name)

不简单。

这是我更新价值的要求

var value = {
  'cluster_importance[0].feature_importance[0].name': 'toto'
}
ClusterImportance.update({
  "_id": bestId,
  "cluster_importance[0].cluster": clusterNumber
}, {
  $set: {
    value
  }
})

我阅读了适用于一个数组而不是两个数组的 mongoose 文档。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    根据你的代码,

    console.log('MyValue',bestClustering.cluster_importance[0].feature_importance[0].name)
    

    假设它输出MyValue John

    使用[..]获取变量的value作为key。

    var value = {
      [bestClustering.cluster_importance[0].feature_importance[0].name]: 'toto'
    }
    ClusterImportance.update({
      "_id": bestId,
      [bestClustering.cluster_importance[0].cluster]: clusterNumber
    }, {
      $set: {
        value
      }
    })
    

    更多示例:

    const mistake = 'key';
    
    const obj1 = { 'mistake': 5}
    console.log(obj1.mistake); // 5
    
    const obj2 = { mistake: 5 }
    console.log(obj2.key) // undefined
    
    const obj3 = { [mistake]: 5 }
    console.log(obj3.key) // 5
    

    【讨论】:

    • 嗨,我测试了你的代码,但节点告诉我 cluster_importance 没有定义。所以我就这样测试。 var value = { '[cluster_importance[0].feature_importance[0].name]': 'toto' } 使用 ' ' 但不起作用:(
    • 我编辑了我的答案,你应该更好地解释你想要达到的key:value 对。
    猜你喜欢
    • 2012-03-28
    • 2016-05-14
    • 2020-11-13
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多