0

I have a route like this :

router.put("/:id", upload.single('doc_upload'), async(req,res)=>{
try{
          const updatedUser = await User.findOneAndUpdate({ "client._id": req.params._id,"clients.documents._id":req.body.doc_id},
          {"$set":{"clients.$[clientFilter].documents.$[documentFilter].status":"uploaded"}},
          {"arrayFilters":[
              {"clientFilter._id":req.params.id},
              {"documentFilter._id":req.body.doc_id}
          ]} ,
          );


for (i=0; i < updatedUser.clients.length; i++) {
            if (updatedUser.clients[i]._id == req.params.id) {
              for (j=0; j < updatedUser.clients[i].documents.length; j++) {
                console.log("this is the status of all my docs" + updatedUser.clients[i].documents[j].status)
                
              }
            }
          }

 res.send(req.file)
 } catch(err){
          res.status(500).json(err);
  }

It first searches for a user then upload the « status » (which is by default « pending »for « uploaded ») My problem is the loop, I’m trying to console log the status of the doc, but even if the update is made in the db it still prints « pending » for all my docs. I guess what I’m trying to do is to find a way to first update the user then console.log everything. Any idea on how to do that please ?

Vaodi
  • 37
  • 6
  • 3
    https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document – 1sina1 Feb 13 '23 at 07:30

1 Answers1

0

As you said you saw db and your required document was updated successfully. Mongoose findOneAndUpdate updates the document but it does not return updated document. To return updated document you should use { new: true } object as additional argument as : let options = { new: true }; DBModel.findOneAndUpdate( findCondition, updateData, options, (error, updatedDoc) => {}); So now since your query returned a updated document, your problem will be solved.