【问题标题】:MEAN stack - GET and POST not querying or saving to mongodbMEAN stack - GET 和 POST 不查询或保存到 mongodb
【发布时间】:2016-08-08 04:30:06
【问题描述】:

我的路线和使用 mongodb 获取/保存数据都有问题。保存或可能不发布 JSON 时似乎存在验证错误。有什么想法吗?

这是我的猫鼬模式:

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var sitesEntrySchema = new Schema({
    ip: {
      type: String,
      required: true,
      trim: true
    },
    domain: {
      type: String,
      required: true,
      trim: true
    },
    wp: {
      type: String,
      required: true,
      trim: true
    },
    host_name: {
      type: String,
      required: true
    },
    hosted: {
      type: Number,
      required: true
    }
});

// make this available to our users in our Node applications
var Site = mongoose.model('Site', sitesEntrySchema);
module.exports = Site;

还有我的角度 http 请求

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, $http) {
    $http.get('/api/mongo')
    .then(function(response) {
        console.log(response.data);
        $scope.myData = response.data;
    });
});

app.controller('FormCtrl', function($scope, $http) {
    $scope.formData = {};

    $scope.addSite = function() {
        $http.post('/api/create', $scope.formData)
            .success(function(data) {
                console.log($scope.formData);
                $scope.formData = {}; // clear the form so our user is ready to enter another
                swal(
                  'Good job!',
                  'Site was added!',
                  'success'
                );
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };
});

我的特快路线:

var express = require('express');
var router = express.Router();
var Site = require('../models/site');

//Return From Mongo
router.get('/api/mongo', function(req, res) {
  Site.find({}, function(err, sites) {
    if (err)
      res.send(err)
    res.send(sites);
  });
  //res.json({"yo": "yo this shit works"});
});

//Add A Site 
router.post('/api/create', function(req, res, next) {
    //create object with form input
    var siteData = {
      ip: req.body.ip, 
      domain: req.body.domain, 
      wp: req.body.wp, 
      host_name: req.body.host_name, 
      hosted: req.body.hosted
    };

    // use schema's 'create' method to insert doc into mongo
    Site.create(siteData, function(error) {
      if (error) {
        //return next(error);
        res.send(error);
      } else {
        return res.json({ message: 'Site added!' });
      }
    });
});

【问题讨论】:

    标签: angularjs mongodb express mongoose mean-stack


    【解决方案1】:

    如果没有显示问题所在的具体输出,这里有一些事情对我来说很重要。第一个并不总是用 json 响应。您还应该尝试使用 next() 来处理您的错误,因为 Express 将确保发回正确的错误响应。通过这些更改,您的获取路线如下所示:

    //Return From Mongo
    router.get('/api/mongo', function(req, res, next) {
      Site.find({}, function(err, sites) {
        if (err) {
          next(err)
        } else {
          return res.json(sites);
        }
      });
    
    });
    

    其次,最好的做法是返回新创建的资源,所以你的创建路线应该是这样的

    //Add A Site 
    router.post('/api/create', function(req, res, next) {
        //create object with form input
        var siteData = {
          ip: req.body.ip, 
          domain: req.body.domain, 
          wp: req.body.wp, 
          host_name: req.body.host_name, 
          hosted: req.body.hosted
        };
    
        // use schema's 'create' method to insert doc into mongo
        Site.create(siteData, function(error, site) {
          if (error) {
            next(error);
          } else {
            return res.json(site);
          }
        });
    });
    

    此外,根据您的 Angular 版本,您可能会在 post 请求中使用已弃用的 promise 语法。您应该使用 .then(),而不是 .success() 和 .error()。这也可能导致问题。

    最后,您应该尽量遵循 REST 指南来处理您的路由和响应。这将使扩展您的网络应用程序变得更加容易,并使您更有条理。这是https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 的一个很好的 Express/Node 资源。

    添加:这是一个示例,说明如何根据生产/开发环境记录错误

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
        console.log('err:', err.status, err.message);
        res.status(err.status || 500);
        res.json({message: err.messages});
      });
    }
    
    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
        message: err.message,
        error: {}
      });
    });
    

    【讨论】:

    • 谢谢@peaches!我清理了我的代码以匹配您的建议,我现在可以创建文档但仍然无法从数据库中获取。错误对象在 next(err) 中时如何查看?
    • @Calrocks 我假设您正在开发中运行您的服务器,可能在本地主机上?查看我的答案的补充内容,了解如何很好地记录错误。如果在本地运行,它们应该在服务器运行的任何地方打印出来。
    猜你喜欢
    • 2016-12-11
    • 2020-05-13
    • 2016-04-14
    • 1970-01-01
    • 2016-03-19
    • 2022-01-05
    • 2022-10-15
    • 2017-08-30
    • 2019-04-30
    相关资源
    最近更新 更多