Question:
How to overwrite the contents of MongoDB via a put request in Nodejs?

Problem

I am following a tutorial and am stuck on the last part of it. I am trying to overwrite the contents of the database via a 'PUT' request.


const express = require("express");

const bodyParser = require("body-parser");

const ejs = require("ejs");

const mongoose = require("mongoose");


const app = express();


app.set('view engine', 'ejs');


app.use(bodyParser.urlencoded({

    extended: true

}));

app.use(express.static("public"));


mongoose.connect("mongodb://localhost:27017/wikiDB", {useNewUrlParser: true});


const articleSchema = {

    title: String,

    content: String

};


const Article = mongoose.model("Article", articleSchema);


// Requests Targeting All Routes


app.route("/articles")


.get(function(req, res) {

    Article.find()

        .then((foundArticles) => {

            mongoose.connection.close();

            foundArticles.forEach(function(foundArticle) {

                // console.log(foundArticle);

                res.send(foundArticles);

            })

        })

        .catch(function(err) {

            console.log(err);

        })

})


.post(function(req, res) {

    const newArticle = new Article({

        title: req.body.title,

        content: req.body.content

    });


    newArticle.save()

        .then(function() {

            res.send("Successfully added a new article.");

        })

        .catch(function(err) {

            console.log(err);

        })

})


.delete(function(req, res) {

    Article.deleteMany()

        .then(() => {

            res.send("Successfully deleted the document.");

        })

        .catch(function(err) {

            console.log(err);

        })

});


// Requests Targeting Specific Routes


app.route("/articles/:articleTitle")

.get(function(req, res) {

    const title = req.params.articleTitle;

    Article.find({title})

        .then((foundArticle)  => {

            res.send(foundArticle);

        })

        .catch(function(err) {

            console.log(err);

        })

})


// It won't allow the contents of the database to be overwritten.

.put(function(req, res) {

    Article.replaceOne({ title: req.params.articleTitle },

        {

          title: req.body.title,

          content: req.body.content,

        })

        .then(() => {

            res.send("Successfully updated article.");

        })

        .catch(function(err) {

            console.log(err);

        })

})

app.listen(3000, function() {

    console.log("Server started on port 3000!");

});


The contents of the database are in this format:


{

    "_id" : ObjectId("6517a22854d8425f4e613d9e"),

    "title" : "REST",

    "content" : "REST is short for REpresentational State Transfer. It's an architectural style for designing APIs."

}


I am trying this in Postman and there is no error. But the problem is that the contents of the database aren't updated. Since there is no error that is shown, it is hard to figure out what the problem is.


Solution

You should use the updateOne API to update a document.


app.route("/articles/:articleTitle")

.put((req, res) => {

  const title = req.params.articleTitle;

  Article.updateOne({

    title

  }, {

    title: req.body.title,

    content: req.body.content,

  })

  .then(() => {

    res.send("Successfully updated article.");

  })

  .catch(function(err) {

    console.log(err);

  });

})


refs

>https://mongoosejs.com/docs/api/model.html#Model.updateOne()


Answered by: >xgqfrms

Credit: >StackOverflow


Blog Links

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during Deployment- Django

>Creating a Django with existing directories, files, etc.?

>How to Read a CSV file with PHP using cURL?


Nisha Patel

Nisha Patel

Submit
0 Answers