如何在MeanStack中使用mongoose在Mongodb中存储值

时间:2017-03-27 13:12:15

标签: angularjs mongodb mongoose mean-stack mongoose-schema

我在mongoose的帮助下使用angularjs db ismongodb .i在mongoose模式中创建一个简单的输入表单,但它显示了 $ http.post(...)。成功不是函数我不知道如何解决这个问题,任何人都有助于如何解决这个问题我是这项技术的新手

Html代码

<!DOCTYPE html>
<html ng-app="App">
<head>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>

    <script src="Controller/MongooseCrud.js"></script>
</head>

<body >

    <div ng-controller="MongooseController">



        <label for="email">Email: </label>
      <input type="email" name="email"  ng-model="user.email" /><br />
    <label for="name">Name: </label>
      <input type="text" name="name" ng-model="user.name" /><br />
    <label for="age">Age: </label>
      <input type="number" name="age" ng-model="user.age"/><br />
      <input type="Button"  value="submit" ng-click="AddNewDetails()">

    </div>



</body>
</html>

控制器

var app = angular.module("App", [ ]);


app.controller('MongooseController', ['$scope', '$http' ,'$window', '$filter',


function ($scope, $http, $window, $filter) {



    $scope.AddNewDetails = function ( ) {

        $http.post('/AddNewDetails',  $scope.user).success(function (response) {


            console.log((response));
        }).error(function (err) {

        });
    };


}]);

Server.js

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema();
var bodyParser = require('body-parser');
var http = require('http');

app.use(express.static(__dirname + "/public"));

app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/crud');

var Schema = new mongoose.Schema({
    _id: String,
    name: String,
    age: Number
});

var user = mongoose.model('emp', Schema);

app.post('/AddNewDetails', function (req, res) {

    console.log(req.body);

    new user({
        email: req.body.email,
        name: req.body.name,
        age: req.body.age


    }).save(function (err, doc) {

        if (err) {
            res.json(err);
        }
        else {
            console.log(doc);
            res.send('Successfully inserted!');
        }
    });
});




app.listen(8082);
console.log("server running on port 8082");

2 个答案:

答案 0 :(得分:0)

您使用的格式不正确。

$ http service https://docs.angularjs.org/api/ng/service/ $ http

就是这样     $ http.get('url')。then(successCallback,errorCallback);

答案 1 :(得分:0)

使用服务......因为你必须将post更改为create。它会给你最好的结果。

&#13;
&#13;
angular.module('yourApp').factory("yourService", function($http){

	return{
		create : function(insertData){
	          return $http.post("http://localhost:yourHost/AddNewDetails/", insertData);
	      }
});
&#13;
&#13;
&#13;