0

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,
    },
  ],
});
1
  • Hardly an "unknown reason". You quite simply have not defined "color" in the schema. So it's being removed. You called it "option" instead. Commented Nov 5, 2017 at 4:50

2 Answers 2

1

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
    }
  ]
});
Sign up to request clarification or add additional context in comments.

1 Comment

That was it, my option: String is dynamic depending on the Poll options, adding strict:false let me save. Cheers!
0

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

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.