ben tedder : code things

Mongoose not saving an array of objects to MongoDB

I was recently having an issue where Mongoose was not saving an array of objects, no matter what I tried. I was using React to send the array that was structured like this:

// NOT WORKING
{
  name: "test",
  age: 14,
  skills: [
    {
      type: "cooking",
      years: 4
    }
  ]
}

Every time I sent that payload, the name and age were applied to the update, but not the skills. Here's what my Mongoose Schema looked like:

// NOT WORKING
{
  name: String,
  age: Number,
  skills: [
    {
      type: String,
      years: Number
    }
  ]
}

After doing a bit of googling and looking around, I realized that the "type" variable name was what was causing the issue. That's a reserved word in Mongoose's schema definition!

I changed the js of the mongoose Schema to:

// WORKING VERSION
{
  name: String,
  age: Number,
  skills: [
    {
      skillType: String,
      years: Number
    }
  ]
}

And everything worked (after changing the payload I was sending of course)! Hope this helps some other poor soul wasting time out there :).