Home > Enterprise >  How to store empty array in mongodb
How to store empty array in mongodb

Time:01-07

I want to store empty array in user schema's friends key. But, mongoose won't let me to add empty array of friends.

Here's my User schema

const userSchema = mongoose.Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  userName: {
    type: String,
    unique: true,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
    validate: [validator.isEmail, "Please enter a valid Email"],
  },
  password: {
    type: String,
    required: true,
    minlength: [6, "Password must be at least 6 characters"],
  },
  friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
      unique: true,
    },
  ],
});

And here's my code to pull data from array and save empty array

const index = req.user.friends.findIndex(friend => friend.toString() === req.params.id);
  
  if(index !== -1){
    req.user.friends.splice(index, 1);
  }else{ 
    req.user.friends.push(req.params.id);
  }

    const user = new User(req.user);

    await user.save({validateBeforeSave: false});
    return res.json({success: true});

CodePudding user response:

specify default value instead

friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
      unique: true,
      default: []
    },
  ],
  •  Tags:  
  • Related