Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (120 points)

Greetings.
I have two fields - One for name and another for number. When submited it gets added to the "phonebook" in the mongoDB. Then it gets displayed in my list on the webpage. everything i have implemented: PUT,DELETE,GET requests, they work all very well, now i tried to implement the solution for UPDATING the number in my "phonebook" When the name is already in the list and we add a new number.
So, When the name matches but the number doesnt, this makes the Number for the name to update. Thus i am using PUT request for this along with findByIdAndUpdate(). But when i make the request, i receive no errors, network headers, success, fail or anything, as if i am not doing anything at all. Been trying to find out my problem but without any success for the past few hours. 

```

require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const app = express();
const cors = require("cors");
const Contact = require("./models/contact");
 
app.use(cors());
app.use(express.json());
app.use(express.static("build"));
 
morgan.token("logger", (reqres=> {
  if (req.method === "POST") {
    return JSON.stringify(req.body);
  }
});
 
app.use(
  morgan(
    ":method :url :status :res[content-length] - :response-time ms :logger"
  )
);
 
//Handle errors for the HTTP requests
const errorHandler = (errorrequestresponsenext=> {
  console.error(error)
 
  if (error.name === 'CastError') {
    return response.status(404).send({error: 'wrong id number'})
  }
 
  next(error)
}
 
//Logs the requests to the console
const requestLogger = (requestresponsenext=> {
  console.log("Method:"request.method);
  console.log("Path:  "request.path);
  console.log("Body:  "request.body);
  console.log("---");
  next();
};
 
app.use(requestLogger);
 
//add new posts to the database
app.post("/api/persons", (requestresponse=> {
  const body = request.body;
 
  if (!body.name || !body.number) {
    response.status(404).json({
      error: "content not found",
    });
  }
 
  const contact = new Contact({
    name: body.name,
    number: body.number,
  })
 
  contact.save().then((savedContact=> response.json(savedContact));
  
});
 
app.put("/api/persons/:id", (requestresponsenext=> {
  const body = request.body
  const id = request.params.id;
  const contact = {
    number: body.number
  }
 
  Contact.findByIdAndUpdate(id, note, {new: true})
    .then((updatedNote=> {
      response.json(updatedNote);
    })
    .catch((error=> next(error));
  
})
 
//Instructions for the response if the /api/persons route is requested.
app.get("/api/persons", (requestresponse=> {
  Contact.find({}).then(result => response.json(result))
});
// If the /info route is requested
app.get("/info", (requestresponse=> {
  const inf = `<h1>Phonebook has info of ${Contact.length} People</h1>`;
  const tme = new Date().toUTCString();
 
  response.write(inf);
  response.write(`<h2>${tme}</h2>`);
  response.end();
});
 
// If the /api/persons/:id is requested
app.get("/api/persons/:id", (requestresponse=> {
  Contact.findById(request.params.id)
        .then(contact => response.json(contact))
});
 
//delete posts using the requested id
app.delete("/api/persons/:id", (request, response, next) => {
  Contact.findByIdAndRemove(request.params.id)
         .then(result => {
           response.status(204).end();
         })
         .catch(error => next(error))
});
 
const unknownEndpoint = (requestresponse=> {
  response.status(404).send({ error: "unknown endpoint" });
};
 
app.use(unknownEndpoint);
app.use(errorHandler);
 
const PORT = process.env.PORT;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```

I import the Contact model from here >
```

const mongoose = require('mongoose');

const url = process.env.MONGODB_URI;
 
console.log('connecting to the database', url);
 
mongoose
  .connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
  })
  .then((result=> {
    console.log("connected to MongoDB");
  })
  .catch((error=> {
    console.log("error connecting to MongoDB:"error.message);
  });
 
  const contactSchema = new mongoose.Schema({
    nameString,
    numberString
  });
 
  contactSchema.set('toJSON', {
    transform: (documentreturnedObject=> {
      returnedObject.id = returnedObject._id.toString();
       delete returnedObject._id;
       delete returnedObject.__v;
    }
  });

  module.exports = mongoose.model('Contact'contactSchema); 

Please log in or register to answer this question.

Browse Categories

...