findByIdAndUpdate

Mongoose - findByIdAndUpdate with req.body

Definition:

db.collection.findOneAndUpdate(filterupdateoptions)

The findOneAndUpdate() method has the following form:

db.collection.findOneAndUpdate(
    <filter>,
    <update document or aggregation pipeline>
    {
      projection<document>,
      sort: <document>,
      maxTimeMS: <number>,
      upsert: <boolean>,
      returnNewDocument: <boolean>,
      collation: <document>,
      arrayFilters: [ <filterdocument1>, ... ]
    }
 ) 

As an Example,

update = async (reqres=> {
    let id = req.body._id;
    let update = req.body;
    
    if (!req.body) {
        return res.status(400).json({
            success: false,
            error: 'You must provide a body to update records.',
        })
    }

    Blog.findByIdAndUpdate(id, {$set:update}, function(errresult){
        if(err){
            console.log(err);
            return res.status(404).json({
                    error,
                    message: 'Blog not updated.',
                })
        }

        return res.status(200).json({
                    success: true,
                    id: Blog._id,
                    message: 'Blog updated successfully.',
                })
    });
}


Result look like this -

1.      {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
1.      config: {url"http://localhost:3005/api/Blog/5dd39979acd5e82e103af5df"method"put"data"{"name":"Anil","rating":"100","_id":"5dd39979acd5e82e103af5df"}"headers: {…}, transformRequest: Array(1), …}
2.      data: {successtruemessage"Blog updated successfully."}
3.      headers: {content-length"54"content-type"application/json; charset=utf-8"}
4.      requestXMLHttpRequest {readyState4timeout0withCredentialsfalseupload: XMLHttpRequestUpload, onreadystatechangeƒ, …}
5.      status200
6.      statusText"OK"
7.      __proto__: Object

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^