简体   繁体   中英

JavaScript: Unable to POST new info to mongodb REST API

I've been working on building a REST API. The purpose of the API is to display information about the planets in the solar system on a local server in .JSON format. I test the URL ( localhost:8000/planets ) using Postman. I can make GET requests but I'm having trouble with POST requests.

I go on Postman, type localhost:8000/planets and make a GET request to bring up my info. Then I change the request type to POST and press Send. Then I click 'Body', choose 'Raw' and then change the format from 'Text' to 'JSON(application/json).

I then enter the data I want to add to the database and press SEND. Now, when I do a second GET request I can see the data I just posted. However, if I make an amendment to the JavaScript file which holds the code for the POST and GET requests etc... and then do a third GET request on Postman, the data I just Posted disappears from the database. I'm new to all this, but I'm under the impression this shouldn't happen. If there's a problem, I'm sure it must be in my code. My code is:

var express = require('express');
var bodyParser = require('body-parser');

var mongoose = require('mongoose');

var app = express();

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

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

mongoose.Promise = global.Promise;
var promise = mongoose.connect('mongodb://localhost/planet_server', {
  useMongoClient: true,
});

promise.then(function(db){
  console.log('DATABASE CONNECTED!!');
}).catch(function(err){
  console.log('CONNECTION ERROR', err);
});

var Schema = mongoose.Schema;

var planetSchema = new Schema({
  name: String,
  position: String,
  moons: String,
  diameterInKm: String,
  daysInYear: String,
  temperature: String
})

var Planet = mongoose.model('Planet', planetSchema);
Planet.collection.drop();


//*****RAW DATA*****

var firstEntry = new Planet({name: "Mercury",
                            position: "Mercury is the first planet in the solar system.",
                            moons: "Mercury has no moons",
                            diameterInKm: "Mercury is 5175km in diameter",
                            daysInYear: "A year on Mercury is a mere 88 days long",
                            temperature: "The surface temperature of Mercury is a scorching 427C!"
});

firstEntry.save(function (err) {
  if (err) {
    return (err);
  }
});

var secondEntry = new Planet({name: "Venus",
                              position: "Venus is the second planet in the solar system.",
                              moons: "Venus has no moons",
                              diameterInKm: "Venus is 12,715km in diameter",
                              daysInYear: "A year on Venus is 225 days long",
                              temperature: "The surface temperature of Venus is a scorching 468C, hot enough to melt lead!"
});

secondEntry.save(function (err) {
  if (err) {
    return (err);
  }
});

var thirdEntry = new Planet({name: "Earth",
                             position: "Earth is the third planet in the solar system.",
                             moons: "Earth has two moons.  No, seriously.  I saw it on QI.",
                             diameterInKm: "Earth is 12,742km in diameter",
                             daysInYear: "A year on Earth is 365.25 days long.  That extra 0.25 is why we have leap years",
                             temperature: "The surface temperature of Earth...well, depends where you live, I guess."
});

thirdEntry.save(function (err) {
  if (err) {
    return (err);
  }
});

var fourthEntry = new Planet({name: "Mars",
                             position: "Mars is the fourth planet in the solar system.",
                             moons: "Mars has two moons, Phobos and Deimos",
                             diameterInKm: "Mars is 6,779km in diameter",
                             daysInYear: "A year on Mars is 687 days long.",
                             temperature: "The surface temperature of Mars is a bracing -55C"
});

fourthEntry.save(function (err) {
  if (err) {
    return (err);
  }
});

var fifthEntry = new Planet({name: "Jupiter",
                             position: "Jupiter is the fifth planet in the solar system.",
                             moons: "Jupiter has 67 moons!",
                             diameterInKm: "Jupiter is 139,822km in diameter",
                             daysInYear: "A year on Jupiter is 4380 days long. If I lived on Jupiter, I wouldn't even be 3 years old.",
                             temperature: "The surface temperature of Jupiter is -145C."
});

fifthEntry.save(function (err) {
  if (err) {
    return (err);
  }
});

var sixthEntry = new Planet({name: "Saturn",
                             position: "Saturn is the sixth planet in the solar system.",
                             moons: "Saturn has 62 moons, 5 less than Jupiter, and is very bitter about it",
                             diameterInKm: "Saturn is 116,464km in diameter",
                             daysInYear: "A year on Saturn is 10,759 days long.",
                             temperature: "The surface temperature of Saturn is -168C."
});

sixthEntry.save(function (err) {
  if (err) {
    return (err);
  }
});

var seventhEntry = new Planet({name: "Uranus",
                              position: "Uranus is the seventh planet in the solar system.",
                              moons: "Uranus has 5 moons",
                              diameterInKm: "Uranus is a relatively svelte 50,724km in diameter",
                              daysInYear: "A Year on Uranus is 30,660 days long.",
                              temperature: "The surface temperature of Uranus is -216C.  That's colder than liquid nitrogen."
});

seventhEntry.save(function (err) {
  if (err) {
    return (err);
  }
});
//*****END OF RAW DATA*****

app.get('/planet', function(req, res){
  console.log(1);
  Planet.find({}).exec(function(err, planet){
    console.log(2);
    if(err) {
      return res.status(500).send(err);
    }
    return res.json(planet);
  });
});

app.post('/planet', function(req, res){
  var newPlanet = new Planet(req.body);
  newPlanet.save(function(err, planet) {
    if(err) {
      return res.status(500).send(err);
    }
    return res.status(201).json(planet);
  });
});

app.listen(8000, function(){
  console.log('Listening');
});

In my latest attempt, I was trying to add data for Neptune. It seemed to work because, like I said, when I made the GET request on Postman after the POST request, I could see the Neptune data along with the data for all the other planets. However, I then noticed a small typo in the JavaScript. I corrected it and saved the JavaScript file and when I made the next GET request the Neptune data was gone. I'm pretty confused so any help you could offer would be gratefully appreciated.

It's because when you reload your js file, you're running the line

var Planet = mongoose.model('Planet', planetSchema);
Planet.collection.drop();

and then adding your initial data again. So the data you POSTed is lost.

Not sure how you're hosting the node file, if you're using nodemon or something to automatically refresh the server when you make a change to the file, but that is what is causing your data to be lost, because it's re-running that drop command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM