【问题标题】:Use a variable in the name of a variable [duplicate]在变量名中使用变量[重复]
【发布时间】:2020-09-22 06:10:16
【问题描述】:

当我使用 quick.db 时,我曾经这样做过:

const table = new require('quick.db').table('table') // quick.db table
let guildID = msg.guild.id // snowflake generated by Discord; let's say it's equal to '1234567890'

table.set(`${guildID}.name`, `Cool Name`) // here, the variable name changes in function of guildID : so, to get 'Cool Name', I would have to look for '1234567890.name'.

我正在尝试在 mongoDB 上做同样的事情。在我看来,它比 quick.db 更好更完整,但我仍然找不到如何在 mongo 上做同样的事情。

我想这可能是不可能的,但我想知道您是否知道我可以如何替换它以轻松获取有关具有相应公会ID的公会的信息。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    感谢将我发送至this page 的评论,我找到了解决方案。

    即使通过这种方法,我也无法创建一个名称直接依赖于变量的值作为文档的字段,我可以在对象内部创建一个值(对象的名称是作为字符串选择的,这就是为什么我可以在那个字符串中插入一个变量)

    collection.updateOne({id: "123"}, {$set: { ["object."+guildID+".name"]: "Cool Name" }}
    

    然后,"Cool Name" 可以通过以下方式找到:

    collection.find({id: "123"}, {"object.1234567890.name": 1}) // note: I don't remember how to get a specific field of a document, please correct me or delete this note if you know what's correct
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      相关资源
      最近更新 更多