简体   繁体   English

平均堆栈环回更新

[英]Mean stack Loopback update

Apologies if this an easy one, I'm relatively new to loopback/ backend, 抱歉,这很简单,对于环回/后端,我还比较陌生,

What I am trying to do is update an existing database records ID and Name with the following code. 我正在尝试使用以下代码更新现有的数据库记录ID和名称。 HTML FILE HTML文件

<div>
  <h1>COMPANY DETAILS</h1>
</div>
<div>
  <div>
    <table>
      <thead>
        <tr>
          <th>Company Name</th>
          <th>Company Code</th>
          <th>Remove</th>
          <th>Edit</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input class="form-control" ng-model="newCompany.name"></td>
          <td><input class="form-control" ng-model="newCompany.id"></td>
          <td><button class="btn btn-primary" ng-click="add()">Add</button></td>
          <td><button class="btn btn-info" ng-click="update()">Update</button></td>
        </tr>
        <tr ng-repeat="company in companies | orderBy:'+name'">
          <td>{{company.name}}</td>
          <td>{{company.id}}</td>
          <td><button class="btn btn-danger" ng-click="remove(company.id)">Remove</button> </td>
          <td><button class="btn btn-warning" ng-click="edit(company)">Edit</button> </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>// This is just a sample script. Paste your real code (javascript or HTML) here.

if ('this_is'==/an_example/){of_beautifier();}else{var a=b?(c%d):e[f];}

JS file JS文件

'use strict';

/**
 * @ngdoc function
 * @name abcApp.controller:CompanyCtrl
 * @description
 * # CompanyCtrl
 * Controller of the abcApp
 */
angular.module('abcApp')
  .controller('CompanyCtrl', ['$scope', 'Company', function ($scope, Company) {
      $scope.newCompany = { 'id': '', 'name': '' };
      $scope.companies = [];
      Company
          .find()
          .$promise
          .then(function (results) {
              $scope.companies = results;
          });

      $scope.update = function (company) {
          company.findById({ id: company })
            .$promise
            .then(function () {                  
                $scope.company.id = 13.40;
                console.log(company.id);
           $scope.company.$save();
       });
      };

      $scope.edit = function (company) {
          $scope.newCompany = { id: company.id, name: company.name };
      }
      $scope.add = function () {
          Company.create($scope.newCompany, function (company) {
              $scope.newCompany = { 'id': '', 'name': '' };
              Company
                  .find()
                  .$promise
                  .then(function (results) {
                      $scope.companies = results;
                  });

          }, function (errorResponse) {
              console.log(errorResponse);
          });
      };

      $scope.remove = function (cid) {
          Company.deleteById({ id: cid })
           .$promise
              .then(function () {
                  console.log('deleted');
                  Company
                          .find()
                          .$promise
                          .then(function (results) {
                              $scope.companies = results;
                          });
              });
      }
  }]);

the $scope.edit function brings the company id and name into two text boxes and the $scope.update function is meant to update the database record, edit function works fine however there is a problem in my $scope.update and when I click on the update button I get the following error in the browser console. $scope.edit函数将公司ID和名称带入两个文本框,而$scope.update函数用于更新数据库记录,edit函数可以正常工作,但是$ scope.update中存在问题,当我单击时在更新按钮上,我在浏览器控制台中收到以下错误。

Unable to set property 'name' of undefined or null reference 无法设置未定义或空引用的属性“名称”

Sorry for the long post any help would be much appreciated 对不起,很长的帖子任何帮助将不胜感激

It looks like you are mixing client-side code and server-side code, the reason why $scope.edit works is because it contains only client side code. 好像您在混合客户端代码和服务器端代码, $scope.edit起作用的原因是因为它仅包含客户端代码。

Mongoose calls (Collection.create, Collection.find ...) should be server-side. 猫鼬调用(Collection.create,Collection.find ...)应在服务器端。


Here's how I would use the MEAN stack in your case : 这是我在您的情况下使用MEAN堆栈的方式:

Mongo is your Database, it contains your documents and collections. Mongo是您的数据库,它包含您的文档和集合。

Express is used to relay your requests from the client to Mongo, using http calls. Express用于通过http调用将您的请求从客户端中继到Mongo。

Angular is the clientside framework, your JS client code will mostly reside inside angular Controllers. Angular是客户端框架,您的JS客户端代码将大部分驻留在angular Controllers中。


Exemple : 范例:

We want all the carots in the database. 我们想要数据库中的所有carot。

Clientside (JS) : 客户端(JS):

angular.module('abcApp')
  .controller('myCarotCtrl', [dependencies,
  function(dependencies) {
     $scope.result = '';
     $scope.getCarrots = function() {
         $http.get('/carrots').
         then(function(data) {
              //Called when the request is successful
              $scope.result = data;
         },
         function(error) {
             //Called when the request failed
             console.log(error)
         }
     }
  }]);

Clientside (HTML) : 客户端(HTML):

<div ng-controller="myController" ng-init="getCarrots()">{{result}}</div>

Server side : 服务器端 :

//assuming express and mongoose have been required/initialized
//using Express to route the requests
//In this exemple request is not used because will dont need parameters
app.get('/carrots', function(request, response) {
    //Use mongoose to access your Carot Collection
    //{} is all documents in the collection
    Carot.find({}, function(err, documents) {
        //send back the documents to the client once they have been found
        response.status(200).send(document);
    });
});

I could not test the code above but I think it will give you some ideas on how the whole stack works. 我无法测试上面的代码,但我认为它将为您提供有关整个堆栈工作原理的一些想法。

company.findById({ id: company }) company.findById({id:company})

Is this a typo? 这是错字吗? Capital C in company ? company资本C? I assume it should be similar to my example at https://github.com/strongloop/loopback-example-angular/blob/master/client/js/controllers/todo.js#L7-L8 我认为它应该与https://github.com/strongloop/loopback-example-angular/blob/master/client/js/controllers/todo.js#L7-L8上的示例相似

Your $scope.update function is wrong from many aspects. 您的$ scope.update函数在很多方面都是错误的。 First because it is expecting you to send company parameter but your are calling method with empty params. 首先,因为它期望您发送公司参数,但是您正在使用空参数调用方法。

This is your method: 这是您的方法:

$scope.update = function (company) {
  company.findById({ id: company })
    .$promise
    .then(function () {                  
        $scope.company.id = 13.40;
        console.log(company.id);
        $scope.company.$save();
  });

}; };

This is your html 这是你的html

<td><button class="btn btn-info" ng-click="update()">Update</button></td>

"company" parameter is undefined so your console gives you an error message (you are using undefined value for findById id parameter - "id: company"). “ company”参数是未定义的,因此您的控制台会显示一条错误消息(您正在使用findById id参数的未定义值-“ id:company”)。

If you want to call update method like this then instead of company parameter you can use your $scope.newCompany variable which already has data that you want to use after you click on edit button. 如果要调用这样的更新方法,则可以使用$ scope.newCompany变量来代替Company参数,该变量已经具有要在单击“编辑”按钮后使用的数据。 That being said your update method should be something like this: 话虽这么说,您的更新方法应该是这样的:

$scope.update = function () {
  Company.findById({ id: $scope.newCompany.id })
    .$promise
    .then(function (company) {
      console.log(company);
      //$scope.company.$save();
    });
};

Second thing to note is that you don't need to write remote "save" method (unless you wrote it for exercise). 要注意的第二件事是,您无需编写远程“保存”方法(除非您为运动而编写)。 Loopback has already generated CRUD methods for you. 环回已经为您生成了CRUD方法。 So if you want to update your model from client use "upsert" method or something similar that best fits your needs. 因此,如果要从客户端更新模型,请使用“ upsert”方法或最适合您需求的类似方法。 See http://localhost:3000/explorer for list of available methods on server. 有关服务器上可用方法的列表,请参见http:// localhost:3000 / explorer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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