Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
How to store empty array in mongodb

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

specify default value instead

friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
      unique: true,
      default: []
    },
  ],
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!