Home > Mobile >  updateOne method not working in express , mongoose
updateOne method not working in express , mongoose

Time:06-26

i m trying to update my db from a put request using updateOne method and following the model and syntax and in call back function i m getting no err instead i m getting the success message but my db is not updating

heres the NodeJS code

const express = require('express')
const bodyparser = require("body-parser")
const mongoose = require("mongoose")
const lodash = require("lodash")
const ejs = require("ejs")
const app = express()
const port = 3000
app.set("view engine", "ejs")
app.use(bodyparser.urlencoded({ extended: true }))
app.use(express.static("public"))
mongoose.connect('mongodb://localhost:27017/wikiDB');

const aritcleSchema = {
    title: String,
    content: String
}

const Article = mongoose.model("Article", aritcleSchema)
const nar = new Article({
        title: "ma balls",
        content: "still itch"
    })
    //nar.save()


app.route('/articles')

.get((req, res) => {
    Article.find({}, (err, foundItems) => {
            if (err) {
                console.log("err")
            } else {
                res.send(foundItems)
                    //console.log(foundItems)
            }
        })
        //res.send('Hello World!')
})

.post((req, res) => {
    const title = req.body.title
    const content = req.body.content
    const newArt = new Article({
        title: title,
        content: content
    })
    newArt.save((err) => {
        if (!err) {
            res.send("u live for now")
        } else { res.send(err) }
    })
    console.log(title, content)
})

.delete((req, res) => {
    Article.deleteMany({}, (err) => {
        if (!err) {
            res.send("bitch you wont get lucky again")
        } else { res.send("you died") }
    })

})

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

.get((req, res) => {
    const id = req.params.articleTitle
    Article.findOne({ title: id }, (err, foundArticle) => {
        if (err) {
            res.send("lpc")
        } else {
            res.send(foundArticle)
        }
    })
})

.put(async function(req, res) {
        let data = await dbconnect()
        Article.updateOne({ title: req.params.articleTitle }, { $set: { title: req.body.title, content: req.body.content } },
            function(err) {
                if (!err) {
                    res.send("Successfully updated the selected article.");
                } else { res.send("you died") }
            }
        );
    })
    // .put((req, res) => {
    //     Article.findOneAndUpdate({ title: req.params.articleTitle }, { title: req.body.title, content: req.body.content }, { overwrite: true }, (err) => {
    //         if (!err) {
    //             res.send("Successfully updated the selected article.");
    //         } else { res.send("you died") }
    //     })
    // })

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

heres the pot man screen shot enter image description here enter image description here enter image description here

  • Copy that URL and Paste it in your mongodb connection.

  • In the below code Cut the MONGO_URL and paste your mongoDB URL for that.

// Create MongoDB Server Connection Path
const mongoose = require("mongoose");

const connectDB = async () => {
    try {
        // Mongodb Connection string
        const con = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex:true
        });

        console.log(`MongoDB connected:${con.connection.host}`);
    } catch (error) {
        console.log(err);
        process.exit(1);
        
    }
}
module.exports = connectDB;
  • Add these code into your server.js file
const connectDB = require("./server/database/connection");
connectDB();

CodePudding user response:

  • 1st You Create your MongoDB Database in MongoDB Site.

enter link description here

  • After take your MongoDB URL.

  • Copy that URL and Paste it in your mongodb connection.

  • In the below code Cut the MONGO_URL and paste your mongoDB URL for that.

// Create MongoDB Server Connection Path
const mongoose = require("mongoose");

const connectDB = async () => {
    try {
        // Mongodb Connection string
        const con = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex:true
        });

        console.log(`MongoDB connected:${con.connection.host}`);
    } catch (error) {
        console.log(err);
        process.exit(1);
        
    }
}
module.exports = connectDB;
  • Add these code into your server.js file
const connectDB = require("./server/database/connection");
connectDB();
  • Related