Home > Enterprise >  Update Operation in MongoDB with NodeJs
Update Operation in MongoDB with NodeJs

Time:03-11

I am working on a Blog WebSite with CRUD operation I am able to achieve CRD operations but have issues with update One.

Issue:-

When I click on the edit button it opens the compose tab with the textfile loaded successfully but when I click on update it redirects to the home page but nothing Update, Please help me get out from this.

//This is the code for edit & Update Route 
        app.get("/posts/:postId/edit", (req, res) => {
      Post.findById(req.params.postId, (err, post) => {
        if (err) {
          console.log(err);
        } else {
          res.render("edit", { post: post });
        }
      });
    });
    app.post("/posts/:postId/edit", (req, res) => {
      Post.findByIdAndUpdate(
        req.params.postId,
        {
          $set: {
            title: req.body.title,
            content: req.body.content,
          },
        },
        (err, update) => {
          if (err) {
            console.log(err);
          } else {
            console.log("Post Updated");
            res.redirect("/");
          }
        }
      );
    });

Form for the Edit/Update

//This is the Edit ejs file containing the update form 
 <form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
            <div >
                <label for="post-title">Title</label>
                <input  id="post-title" name="postTitle" type="text" placeholder="Input title"
                    required autocomplete="off" value="<%=post.title%>">
            </div>
            <div >
                <label for="postcontent">Post</label>
                <textarea  id="postcontent" name="blog" rows="4" cols="50" required
                    placeholder="Start writing your blog ..............."><%=post.content%></textarea>
            </div>
            <button  type="submit" name="button">Update</button>
        </form>

CodePudding user response:

Your error is from the Ejs

You didn’t rename your req.body well to match your incoming data

You were meant to be used title instead of postTitle

And content instead of blog

Just edit your ejs to this and test gee

 <form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
        <div >
            <label for="post-title">Title</label>
            <input  id="post-title" name=“title" type="text" placeholder="Input title"
                required autocomplete="off" value="<%=post.title%>">
        </div>
        <div >
            <label for="postcontent">Post</label>
            <textarea  id="postcontent" name="content" rows="4" cols="50" required
                placeholder="Start writing your blog ..............."><%=post.content%></textarea>
        </div>
        <button  type="submit" name="button">Update</button>
    </form>

If this answers your question mark it as done

  • Related