findbyIdAndUpdate not working when there is addition of records in collection findbyIdAndUpdate not working when there is addition of records in collection mongoose mongoose

findbyIdAndUpdate not working when there is addition of records in collection


Usually, we can update a single record in multiple ways

  1. findOneAndUpdate() method is used for update a record in collection. it is good to use this method because another way to perform the same operation is first found the record and then update. It saves time. It contains an option flag like new: true by which it will return updated record in response.
    User.findOneAndUpdate({_id: id},{$set:{name:user.name}},{new:true}).then((docs)=>{        if(docs) {           resolve({success:true,data:docs});        } else {           reject({success:false,data:"no such user exist"});        }    }).catch((err)=>{       reject(err);    });
  1. findByIdAndUpdate() method is used to update record based on Id. Where we can pass the id as «Object|Number|String» value of _id to query. So here, directly we can pass req.params.id
    User.findByIdAndUpdate(req.params.id,{$set:{name:user.name}},{new:true}).then((docs)=>{       if(docs) {         resolve({success:true,data:docs});       } else {         reject({success:false,data:"no such user exist"});       }    }).catch((err)=>{        reject(err);    })


Although you don't have to pass id in the form of an object it seems the culprit is in req.params.uid.Double-check if uid is really set on the req.params and it's correct in a sense that it points to a document in your collection.For the moment that's the only obvious reason that explains why you get null back.You can check that through mongo shell using db.collection.find(<query>).


Your usage of findByIdAndUpdate doesn't seem to be correct, the first argument is supposed to be an id (mongodb object ID or just a string) instead of an object. I would try this first

this._model.findByIdAndUpdate(req.params.uid, updatevalue, options, (err, obj) => {    if (err) {        res.send(err);    }    else {       res.send(obj);    }});

Alternatively, if you want to use query as the filter in your code, then you can use findOneAndUpdate instead. Detailed doc is here.