Gabriel Donada
Gabriel Donada

Reputation: 449

How to push a value to an array using NodeJS and Mongoose

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

Upvotes: 0

Views: 51

Answers (2)

hoangdv
hoangdv

Reputation: 16147

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

Upvotes: 1

aldison
aldison

Reputation: 57

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

Upvotes: 1

Related Questions