Home > Software design >  Mongoose - update a value with find by id
Mongoose - update a value with find by id

Time:01-26

I try to getting all post clicked from my front-end, so req.body.numberOfClick is the value contain number of click & his ObjectID : req.body._id

app.post('/allPostClicked', function (req, res){
  console.log("ID : " req.body._id, ", Number of click : " req.body.numberOfClick);

});

i got successfully some result :

...
ID : 63b0996c5fac5d36a035bfe1 , Number of click : 23
ID : 63b0996c5fac5d36a035bfe1 , Number of click : 24
ID : 63a98cefd003d6794bb12858 , Number of click : 1
ID : 63b0996c5fac5d36a035bfe1 , Number of click : 25
ID : 63b0996c5fac5d36a035bfe1 , Number of click : 26

Now, i need to store that on my Mongo database, so i would like to find with _id which field depending that, for put the new value on his getNumberOfClick's field

app.post('/allPostClicked', function (req, res){
  console.log("ID : " req.body._id, ", Number of click : " req.body.numberOfClick);
try{
  const filter = { _id: req.body._id };
  const update = { getNumberOfClick: req.body.numberOfClick };


Post.findOneAndUpdate( filter, update )

}catch{
 res.status(404).send({error: "Post is not find !"})
}

 res.end("yes");
});

unfortunately, i doesn't have any update on this column

enter image description here

CodePudding user response:

When you query your database, you have to use async/await to "await" the result, or use a callback, for ex with async/await:

app.post('/allPostClicked', async function (req, res){
  console.log("ID : " req.body._id, ", Number of click : " req.body.numberOfClick);
try{
  const filter = { _id: req.body._id };
  const update = { getNumberOfClick: req.body.numberOfClick };

  const result = await Post.findOneAndUpdate(filter, update)
     if(!result) {
     res.status(404).send({error: "Post is not find !"})
  }
}catch(err){
 res.status(500).send({error: err })
}
 res.end("yes");
});

Ofc if you have already stored some data in your database before you try to find it. In case if you want to insert the document when is not found, you can also add an insert option like this

const result = await Post.findOneAndUpdate(filter, update, {upsert: true})

But in this case you won't get the error message document not found, since it will create one instead, so it's up to you. For more detail you can check in their documentation: https://mongoosejs.com/docs/api.html#model_Model-findOneAndUpdate

  • Related