0

I'm trying to update an array that is available on my MongoDB. I tried the way below but I reive the message "Cannot read property push of undefined"

router.get("/candidatarse/:id", eCandidato, (req,res)=>{
Vaga.findOne({_id: req.params.id}).then((vaga)=>{
    
    vaga.candidatos.push(req.user._id)

    vaga.save().then(()=>{
    req.flash("success_msg","Você se candidatou com sucesso! Continue encaminhando seu curriculo.")
    res.redirect("/")
}).catch((err)=>{
    req.flash("error_msg", "Houve um erro ao cadastrar candidatura: "+err)
    res.redirect("/")
})
})

})

I also tried adding a position but didn't worked: vaga.candidato[0].push(req.user.id)

Here is how I have created the model: enter image description here

1
  • what is any property in schema? Commented Jun 20, 2021 at 5:17

2 Answers 2

1

Check vage object, if it already includes candidatos just push new item to this array, else create new array for candidatos

if (Array.isArray(vaga.candidatos) {
  vaga.candidatos.push(req.user._id);
} else {
  vaga.candidatos = [req.user._id];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, looks like that worked, but the data has been not inserted. Looking in MongoDB I received an Object, but there is no data available after inserting it. I've checked and there is data when inserting, but that is not saving. I also tried to change the model to 'type: Array'. Do you know how can I fix it?
I used "Object.values(JSON.parse(JSON.stringify(vaga.candidatos)))" and worked, thanks for your help
1

At the line 16, im not sure if "any: array" exist because any and array are two data types. Try to remove that line.

1 Comment

The guy above helped regarding adding, but that is not adding exactly, as I mentioned on the comments, I guess that it is connected with what you said, I tried changing the model to 'Array' only, and I received an error saying that cannot cast, so I tried to String as well and didn't worked as well.

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.