如何在我的Node.js应用程序中合并模型和控制器?

时间:2016-01-24 22:49:21

标签: javascript node.js mongodb model-view-controller

所以我正在尝试将数据库功能添加到我的简单网站中,这令我感到沮丧。我可以使用一个基本的控制器,但是一旦我加入模型就会引起混乱。如果控制器在客户端运行,我该如何导入我的模型?我无法使用require,因为它是服务器端的。然而,无论我在网上看到什么,他们只需在控制器中使用require。我在哪里存储我的模型和控制器,以及如何将它们正确地合并到我的视图中?我所假设的是模型和控制器必须以某种方式在服务器端使用,然后将信息传递给视图。如果这是一个混乱,我必须在这里错过一个大概念。我对所有这些部分如何相互作用有一个可怕的理解,我觉得这是由于我对这些东西的知识存在巨大差距。如果有人能够联系好资源以更好地理解这些东西的基本原理,那么我就会停止犯这些愚蠢和令人沮丧的错误,我真的很感激:)非常感谢你们和女士们

型号:

var mongoose = require("mongoose");

var PostSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    imgUrl: {
        type: String,
        required: true
    },
    uploadDate: {
        type: Date,
        required: true
    },
    lastUpdated: {
        type: Date,
        required: true
    }
});

PostSchema.pre("save", function(next) {
    var currentDate = new Date();

    if(!this.uploadDate) {
        this.uploadDate = currentDate;
    }

    this.lastUpdated = currentDate;

    next();

});

var Post = mongoose.model("Post", PostSchema);

module.exports = Post;

查看:

head.jade:

//- CSS
link(href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet")
link(href="stylesheets/style.css" rel="stylesheet")

//- Scripts
script(src="bower_components/angular/angular.min.js")
script(src="bower_components/jquery/dist/jquery.min.js")
script(src="bower_components/bootstrap/dist/js/bootstrap.min.js")
script(src="app/app.js")

title #{title} | Vagablog

layout.jade:

doctype html
html(ng-app="app")
    head
        include head.jade
        block scripts

    body
        .container-fluid
            .row
                .col-xs-12
                    #logo-container
                        img(class="img-responsive" id="logo" src="../images/logo.png")
            include nav.jade
            block content
            block footer

index.jade:

extends partials/layout

block scripts
    script(src="app/controllers/PostCtrl.js")

block content
    div(ng-controller="PostCtrl")
        .row
            .col-xs-9
                #main
                    .row
                        .col-xs-12
                            form(class="form-horizontal" ng-submit="post(title, content, image)")
                                .form-group
                                    label(for="inputTitle" class="col-sm-2 control-label") Title
                                    .col-sm-10
                                        input(required type="text" class="form-control" id="inputTitle" placeholder="Title" ng-model="title")
                                .form-group
                                    label(for="inputContent" class="col-sm-2 control-label") Content
                                    .col-sm-10
                                        textarea(required class="form-control" id="inputContent" placeholder="Content" ng-model="content")
                                .form-group
                                    label(for="inputImg" class="col-sm-2 control-label") Image URL
                                    .col-sm-10
                                        input(required type="text" class="form-control" id="inputImg" placeholder="Image URL" ng-model="image")
                                .form-group
                                    .col-sm-offset-2.col-sm-10
                                        button(type="submit" class="btn btn-default") Post

                    .row
                        .col-xs-12
                            div(ng-repeat="post in getPosts()")
                                hr
                                .well
                                    h2 {{ post.title }}
                                    h4 {{ post.content }}
                                    img(src="{{ post.imgUrl }}")
                                    p Uploaded: {{ post.uploadDate }}
                                    p Last Updated: {{ post.lastUpdated }}

            .col-xs-3
                .row
                    .col-xs-12
                        #sidebar
                            .well(style="height: 500px;")

block footer
    .row
        .col-xs-12
            hr
            .footer
                h4(class="copyright") Footer

控制器:

(function() {

    var Post = require("../models/post");

    var PostCtrl = function ($scope, $log, $location) {

        $scope.post = function (postTitle, postContent, postImage) {

            var newPost = Post({
                title: postTitle,
                content: postContent,
                imgUrl: postImage,
                uploadDate: new Date(),
            });

            newPost.save(function(err) {
                if (err) {
                    throw err;
                };
            });

        };

        $scope.getPosts = function() {

            Post.find({}, function(err, posts) {
                if (err) {
                    throw err;
                };

                return posts;

            });

        };
    };

    app.controller("PostCtrl", ["$scope", "$log", "$location", PostCtrl]);

})();

许多错误:

ReferenceError: require is not defined
 PostCtrl.js:3:6

"Error: [ng:areq] http://errors.angularjs.org/1.4.9/ng/areq?p0=PostCtrl&p1=not%20a%20function%2C%20got%20undefined

GET 
http://localhost:3000/%7B%7B%20post.imgUrl%20%7D%7D  [HTTP/1.1 500 Internal Server Error 4ms]

1 个答案:

答案 0 :(得分:0)

您遇到的问题是混合客户端和服务器代码。您要做的是创建一个API,公开客户端应用可以访问的路由。这些路由将返回mongoose查询。

article应提供设置API服务器所需的一切

关于您的客户端代码,您将要创建具有角度的工厂,这些工厂具有针对每个相应端点的功能。在这些函数中,您可以利用$http服务来读取和更改资源中的数据。这可以这样做:

angular.module('myApp')
.factory('bearsFactory', ['$http', function($http) {
  var urlBase = 'localhost:9000/api/bears';

  return {
    getBears: function () {
      return $http.get(urlBase);
    },

    getBear: function (id) {
      return $http.get(urlBase + '/' + id);
    },

    createBear: function (bear) {
      return $http.post(urlBase, bear);
    },

    updateBear: function (bear) {
      return $http.put(urlBase + '/' + bear.ID, bear)
    },

    deleteBear: function (id) {
      return $http.delete(urlBase + '/' + id);
    }
  }
}]);

然后在您的控制器中,您可以像这样利用这些工厂:

angular.module('myApp')
.controller('bearController', ['$scope', 'bearsFactory', function ($scope, bearsFactory) {
  $scope.getBears() {
    bearsFactory.getBears()
    .success(function (bears) {
      $scope.bears = bears;
    })
    .error(function (error) {
      $scope.status = 'Unable to load bear data: ' + error.message;
    });
  }
}]);