【问题标题】:How should i fetch a random field of a mongoose schema?我应该如何获取猫鼬模式的随机字段?
【发布时间】:2021-08-21 18:01:39
【问题描述】:
const myschema = new mongoose.schema({
  userID: message.author.id,
  BookesPages: {
    Fallingforyou: {type: Number, default: '685'},
    Intheblack: {type: Number, deafult: '369'}
  },
})

这是一个示例代码,我应该如何随机增加其中任何一个

【问题讨论】:

    标签: javascript mongoose discord discord.js mongoose-schema


    【解决方案1】:

    您可以将所有字段名称放在一个数组中。然后使用一个函数随机生成该数组中索引的编号。之后,您可以使用该索引处的数组值作为您要访问的随机键。

    这是一个例子:

    // just using regular object here, since we can't use mongoose on stack overflow
    const myschema = {
      userID: "412341234",
      BookesPages: {
        Fallingforyou: {
          type: Number,
          default: '685'
        },
        Intheblack: {
          type: Number,
          deafult: '369'
        }
      },
    }
    
    // array of schema keys
    const schemaKeys = ['userID', 'BookesPages']
    
    // get a random value from values in an array
    const getRandomValue = (array) => {
      const index = Math.floor(Math.random() * array.length)
      
      return array[index]
    }
    
    // get random key
    const key = getRandomValue(schemaKeys)
    
    // now you can get the value corresponding to the random key in your schema
    console.log(myschema[key])

    这不适用于子文档,例如 Fallingforyou 或 Intheblack。你必须使用递归来获得这些。

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2017-06-05
      • 1970-01-01
      • 2021-08-14
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多