Musa
Musa

Reputation: 583

Saving Array of Obj in Mongoose

I have an Express endpoint that you can POST to that looks like:

router.post("/add", (req, res) => {
  Poll.create({
    question: req.body.question,
    options: req.body.options,
  }).then(p => {
    res.send(p);
  });
});

This is what I am trying to POST:

{
    "question": "what is your favourite colour?",
    "options" : 
    [
    {
        "colour" : "green",
        "votes" : 5
    },
    {
        "colour": "red",
        "votes": 50
    }
    ]
}

The response I am receiving is:

{
    "__v": 0,
    "question": "what is your favourite colour?",
    "_id": "59fe97088687d4f91c2cb647",
    "options": [
        {
            "votes": 5,
            "_id": "59fe97088687d4f91c2cb649"
        },
        {
            "votes": 50,
            "_id": "59fe97088687d4f91c2cb648"
        }
    ]
}

For some reason the "colour" key is not being captured. I confirmed this by viewing the collection in Mongo, and indeed there is only "votes" captured and no colours.

And just in case it helps here is the Model Schema:

const PollSchema = new Schema({
  question: {
    type: String,
  },
  options: [
    {
      option: {
        type: String,
      },
      votes: Number,
    },
  ],
});

Upvotes: 0

Views: 41

Answers (2)

TGrif
TGrif

Reputation: 5931

If you need to save properties that you do not have planned in your schema, you can add the
{ strict: false } option to it. This way, the properties will be saved.

const PollSchema = new Schema({
  // ... your schema
}, { strict: false });

But if you know that the property will always the same, it's best to add it to your schema definition.

const PollSchema = new Schema({
  question: String,
  options: [
    {
      colour: String,
      votes: Number
    }
  ]
});

Upvotes: 1

Michael Chen
Michael Chen

Reputation: 51

It is because you did not add "colour" to the schema. So Mongoose? will ignore "colour", therefore it will not be on your DB.

Upvotes: 0

Related Questions