Search code examples
mongodbphotoavatar

default value in MongoDB


I was wondering if it is possible to set a default value choosing from a array of elements.. For example:

    const userSchema = new mongoose.Schema({
       username: {
      type: 'String',
      require: [ true, "Please choose a username!" ],
      trim: true,
      unique: true
   },
   
   ...etc ...
   .....
    avatar: {
      type: 'String',
      default: '[FOR EXAMPLE HERE, TO TAKE RANDOMLY A VALUE FROM A LIST]'
   },

To be more precise, I want to design a couple of avatar logos for the users that don't select a photo for their avatars. So I want to have a list, with the picture urls. so ..it's possible to randomly choose a default value from a list?


Solution

  • you can create a function to randomly assign from the list

      avatar: {
      type: 'String',
      default: function() {
        return avatarArrayList[Math.floor(Math.random()*avatarArrayList.length)];
      }
    },
    

    for more info check https://mongoosejs.com/docs/defaults.html