我应该如何获取猫鼬模式的随机字段?

时间:2021-06-03 15:30:51

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

const myschema = new mongoose.schema({
  userID: message.author.id,
  BookesPages: {
    Fallingforyou: {type: Number, default: '685'},
    Intheblack: {type: Number, deafult: '369'}
  },
})

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

1 个答案:

答案 0 :(得分:0)

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

这是一个例子:

// 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。你必须使用递归来获得这些。

相关问题