Random id generation on form save mongoose
You are using the wrong update method, instead of findOneAndUpdate()
which expects a query object as the first argument (you are giving it a string), you need the findByIdAndUpdate()
method which takes in a string id as first parameter.
findByIdAndUpdate(id, ...)
is equivalent to findOneAndUpdate({ _id: id }, ...)
If using findOneAndUpdate()
to query on a different field other than the model's _id
key, say on the user
field, then you can restructure the code to reflect:
// competition form details postrouter.post('/dashboard/users/forms/competition-form/:id', (req, res) => { CompetitionForm.findOneAndUpdate( {user: req.params.id}, // <-- query object req.body, {upsert:true}, (err, competition) => { if (err) { console.log(`Error saving data: ${err}`); return res.send('Error saving data'); } res.redirect('/dashboard'); console.log(req.body); });});