【问题标题】:nodeJS method giving error even after the JSON data is persisted on MongoDB即使在 JSON 数据保存在 MongoDB 上之后,nodeJS 方法也会出错
【发布时间】:2016-10-20 07:23:47
【问题描述】:

我是 nodeJS 和 mongoDB 的新手。使用 nodeJS 作为中间件,mongoDB 作为数据库,在 UI 中使用 angularJS 创建应用程序。

在 nodeJS 中具有控制器和模型到业务逻辑以及持久化数据。目前的问题是即使在将对象插入数据库(来自模型)之后控制器也会出错。

控制器代码如下:

router.post("/add", function(req,res){
var student = req.body;
Students.add(student, function(err) {
if (err) {
  throw err;
}
var respOut = JSON.stringify({id:student.id});
console.log("respOut");
res.send(respOut);
});
});

型号代码:

exports.add = function(student, cb) {
var collection = db.get().collection('students');
collection.insert(student, function(err) {
if (err) {
   throw err;
}
console.log("Record added");
});
}

在 UI 端使用下面的 angularJS 代码将数据提交给 nodeJS 控制器:

mainApp.controller("addStudentController", function($scope,$http) {
var resData = {};
$scope.output = "";
var url = "/students/add";
$scope.addStudent = function(){
    $http.post(url, $scope.student)
    .success(function(data, status, headers, config) {
        resData = angular.fromJson(data);
        $scope.output = "Student entered successfully with unique Id "+resData.id;
    }).error(function(data, status, headers, config) {
        resStatus = status;
        $scope.output = "Something went wrong. Please try again later."
    });
}
});

请帮忙!!!!!!

【问题讨论】:

    标签: jquery angularjs node.js express


    【解决方案1】:

    一旦在控制器中检查它是否是student._id,因为节点默认创建以“_”为前缀的id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2018-11-25
      • 2014-06-30
      • 1970-01-01
      • 2018-05-24
      • 2015-10-02
      相关资源
      最近更新 更多