1

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});

1 Answer 1

2

specify default value instead

friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
      unique: true,
      default: []
    },
  ],
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.