Как создать функцию PUT в AngularJS с помощью Mongoose - PullRequest
0 голосов
/ 03 июня 2019

Запрос GET к Mongo работает, но PUT не работает, и я подозреваю, что путь от контроллера к маршрутизатору плох. Я пытался использовать update() и findByIdAndUpdate() без удачи. Я не попадаю на маршрутизатор, и если я это сделаю, я не вижу обновленных данных в Mongo. Я использую экспресс, нод и мангуст.

retail.controller.js


  myApp.controller("RetailController", [
      "RetailService",
      "$routeParams",
      "$http",
      function(RetailService, $routeParams, $http) {
        var self = this;

        //self.isBusy = true;

        self.getMovies = function(id) {
          self.getDetails(id);
          self.getApiMovies(id);
        };

        // Get data from MongoDB Movies Table
        self.getDetails = function(id) {
          $http({
            method: "GET",
            url: "/movies/data_store/" + id
          }).then(function(response) {
            self.productData = response.data[0];
            console.log(self.productData);
          });
        };

        self.getApiMovies = function(id) {
          $http({
            method: "GET",
            url: "/movies/api/" + id
          }).then(function(response) {
            let data = response.data.product.item;
            self.apiData = data;
          });
        };

        self.updatePrice = function(id, data) {
          $http({
            method: "PUT",
            url: "/update/" + id,
            data
          }).then(function(response) {
            console.log(response);
          });
        };
      }
    ]);

retail.router.js

var express = require("express");
var router = express.Router();
var MyRetail = require("../models/myretail.schema");
var request = require("request");

// Data route to API
router.get("/api/:id", function(req, res) {
  var apiURL = "http://redsky.target.com/v2/pdp/tcin/13860428?price";

  request(apiURL, function(error, response, body) {
    if (error) {
      console.log("error making Redsky API request");
      res.sendStatus(500);
    } else {
      res.send(body);
    }
  });
}); // End route to API

// Data route to dB with :id
router.get("/data_store/:id", function(req, res) {
  MyRetail.find({ id: req.params.id }, function(databaseQueryError, data) {
    if (databaseQueryError) {
      console.log("database query error", databaseQueryError);
      res.sendStatus(500);
    } else {
      res.send(data);
    }
  });
}); // End data route to dB with :id

router.put("/update/:id", function(req, res) {
  console.log(req.body.current_price.value);
  console.log(req.body._id);

  MyRetail.findByIdAndUpdate(
    { id: req.body._id },
    { $set: { "current_price.$.value": req.body.current_price.value } }
  ),
    function(databaseQueryError, data) {
      console.log(data);
      if (databaseQueryError) {
        console.log("database query error", databaseQueryError);
        res.sendStatus(500);
      } else {
        res.send("data updated");
      }
    };
});

module.exports = router;

Я ищу помощь или толчок в правильном направлении, чтобы завершить PUT

1 Ответ

0 голосов
/ 03 июня 2019

Angularjs Сервис:

 self.updatePrice = function(id, data) {
          var URL = "/update/" + id;
          $http.put( URL, data).then(function (response,error) {
               if (error) {
                    console.log('error : '+JSON.stringify(error));
               } else {
                   console.log('response : '+JSON.stringify(response));
               }
           })
    };

Сторона сервера:

router.put('/update/:id', function(req, res) {
   console.log(req.body.current_price.value);
   console.log(req.body._id);
   MyRetail.update(
      { id: req.body._id },
      { $set: { "current_price.0.value": req.body.current_price.value } }
   ,function(databaseQueryError, data) {
      console.log(data);
      if (databaseQueryError) {
          console.log("database query error", databaseQueryError);
          res.sendStatus(500);
          res.json({message  : "data not updated"});
      } else {
         res.json({message  : "data updated"});
      }
    });
  });

Попробуйте это! Пожалуйста, укажите имя переменной / поля

для $ оператор читает документацию вам нужно иметь current_price в поиске запроса.

...