Skip to content

Instantly share code, notes, and snippets.

@MawiraIke
Created November 17, 2019 11:59
Show Gist options
  • Save MawiraIke/5795903d9776dbb98dc96649d2f1babc to your computer and use it in GitHub Desktop.
Save MawiraIke/5795903d9776dbb98dc96649d2f1babc to your computer and use it in GitHub Desktop.
let bodyParser=require("body-parser")
let mongoose=require("mongoose")
//connect to database
mongoose.connect("mongodb://<Atlas>:<name>@cluster0-shard-00-00-6saai.mongodb.net:27017,cluster0-shard-00-01-6saai.mongodb.net:27017,cluster0-shard-00-02-6saai.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority"
, {useNewUrlParser:true,useUnifiedTopology:true})
//create a schema - this is like a blueprint
let todoSchema=new mongoose.Schema({
item: String
})
//create a model
let Todo=mongoose.model("Todo",todoSchema)
// let data=[{item:"Get milk"}, {item:"Meeting with boss"}, {item:"Code Node Js"}]
let urlEncodedBodyParser=bodyParser.urlencoded({extended:false})
module.exports=function(app){
app.get("/todo",function(req, res){
//get data from Mongo DB and pass it to the view
Todo.find({}, function(err, data){
if(err) throw err
res.render("todo", {todos:data})
})
})
app.post("/todo", urlEncodedBodyParser, function(req, res){
//get data from the view and add it to the Mongo DB
let newTodo=Todo(req.body,function(err, data){
if(err) throw err
res.json(data)
})
})
app.delete("/todo/:item",function(req, res){
//delete the requested item from the database
Todo.find({item:req.params.item.replace(/\-/g, " ")}).remove(function(err, data){
if(err) throw err
res.json(data)
})
})
}
@MawiraIke
Copy link
Author

MawiraIke commented Nov 17, 2019

  1. Is the MongoDB connection active? I'd suggest a callback in the connect query to specify if its running. e.g.
mongoose.connect("databaseUrl", {
    useNewUrlParser: true
}, (error) => {
    if (error) {
        logger.log('error', 'Mongoose connection error: ' + error);

    } else {
        console.log("Connected to mongodb")
    }
});

If that's working I'd suggest you upload the HTML post or AJAX post here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment