JavaScript:无法将新信息发布到mongodb REST API

时间:2017-10-23 05:51:48

标签: javascript json mongodb rest

我一直致力于构建REST API。 API的目的是以.JSON格式在本地服务器上显示有关太阳系中行星的信息。我使用Postman测试URL(localhost:8000/planets)。我可以发出GET请求,但我遇到POST请求有问题。

我继续邮递员,输入localhost:8000/planets并发出GET请求以显示我的信息。然后我将请求类型更改为POST,然后按发送。然后点击' Body',选择' Raw'然后从'文本'更改格式到' JSON(application / json)。

然后我输入要添加到数据库的数据,然后按SEND。现在,当我做第二个GET请求时,我可以看到刚发布的数据。但是,如果我修改了保存POST和GET请求等代码的JavaScript文件......然后在Postman上做第三个GET请求,我刚发布的数据就会从数据库中消失。我对这一切都很陌生,但我认为这不应该发生。如果出现问题,我确定它必须在我的代码中。我的代码是:

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');
});

在我最近的尝试中,我试图为海王星添加数据。它似乎有效,因为,正如我所说,当我在POST请求后在Postman上发出GET请求时,我可以看到海王星数据以及所有其他行星的数据。但是,我注意到JavaScript中的一个小错字。我纠正了它并保存了JavaScript文件,当我发出下一个GET请求时,Neptune数据消失了。我很困惑,所以你能给予的任何帮助都会感激不尽。

1 个答案:

答案 0 :(得分:0)

这是因为当你重新加载你的js文件时,你正在运行这行

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

然后再次添加初始数据。因此,您发布的数据将丢失。

如果您在对文件进行更改时使用nodemon或其他东西自动刷新服务器,则不确定您是如何托管节点文件的,但这是导致数据丢失的原因,因为它是重新运行该drop命令。