在CRUD模型MEAN.js中创建字段

时间:2016-11-08 09:42:28

标签: angularjs node.js mongodb meanjs

我从MEAN.js框架开始,我正在尝试创建我的第一个应用程序。我正在使用Yeoman生成的CRUD模块创建应用程序(yo meanjs:crud-module)。

该应用是一个包含2个字段的简单表单。 “名称”和“图像”。名称是图像的标题,图像是图像的URL。

我现在的问题是我无法在表单中插入Mongo集合“照片”这两个字段。只有CRUD模块生成器默认生成的字段“name”才能正确插入集合中。 我做错了什么?

photo.server.model.js

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Photo Schema
 */
var PhotoSchema = new Schema({
  name: {
    type: String,
    default: '',
    required: 'Introduce el nombre de la imagen',
    trim: true
  },
  image: {
    type: String,
    default: '',
    required: 'Introduce la url de la imagen',
    trim: true
  },
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Photo', PhotoSchema);

photo.server.controller.js

'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Photo = mongoose.model('Photo'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Photo
 */
exports.create = function(req, res) {
  var photo = new Photo(req.body);
  photo.user = req.user;
  photo.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      res.jsonp(photo);
    }
  });
};

/**
 * Show the current Photo
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var photo = req.photo ? req.photo.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  photo.isCurrentUserOwner = req.user && photo.user && photo.user._id.toString() === req.user._id.toString();

  res.jsonp(photo);
};

/**
 * Update a Photo
 */
exports.update = function(req, res) {
  var photo = req.photo;

  photo = _.extend(photo, req.body);

  photo.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(photo);
    }
  });
};

/**
 * Delete an Photo
 */
exports.delete = function(req, res) {
  var photo = req.photo;

  photo.remove(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(photo);
    }
  });
};

/**
 * List of Photos
 */
exports.list = function(req, res) {
  Photo.find().sort('-created').populate('user', 'displayName').exec(function(err, photos) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(photos);
    }
  });
};

/**
 * Photo middleware
 */
exports.photoByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Photo is invalid'
    });
  }

  Photo.findById(id).populate('user', 'displayName').exec(function (err, photo) {
    if (err) {
      return next(err);
    } else if (!photo) {
      return res.status(404).send({
        message: 'No Photo with that identifier has been found'
      });
    }
    req.photo = photo;
    next();
  });
};

photo.client.controller.js

(function () {
  'use strict';

  // Photos controller
  angular
    .module('photos')
    .controller('PhotosController', PhotosController);

  PhotosController.$inject = ['$scope', '$state', '$window', 'Authentication', 'photoResolve'];

  function PhotosController ($scope, $state, $window, Authentication, photo) {

    var vm = this;

    vm.authentication = Authentication;
    vm.photo = photo;
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;

    // Remove existing Photo
    function remove() {
      if ($window.confirm('Are you sure you want to delete?')) {
        vm.photo.$remove($state.go('photos.list'));
      }
    }

    // Save Photo
    function save(isValid) {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.photoForm');
        return false;
      }
      // TODO: move create/update logic to service
      if (vm.photo._id) {
        vm.photo.$update(successCallback, errorCallback);
      } else {
        vm.photo.$save(successCallback, errorCallback);
        //console.log(vm.photo.image);
      }

      function successCallback(res) {
        $state.go('photos.view', {
          photoId: res._id
        });
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }
  }
}());

形状photo.client.view.html

<section>
  <div class="page-header">
    <h1>{{vm.photo._id ? 'Edit Photo' : 'Nueva imagen'}}</h1>
  </div>
  <div class="col-md-12">
    <form name="vm.form.photoForm" class="form-horizontal" ng-submit="vm.save(vm.form.photoForm.$valid)" novalidate>
      <fieldset>
        <div class="form-group" show-errors>
          <label class="control-label" for="name">Nombre</label>
          <input name="name" type="text" ng-model="vm.photo.name" id="name" class="form-control" placeholder="Name" required>
          <div ng-messages="vm.form.photoForm.name.$error" role="alert">
            <p class="help-block error-text" ng-message="required">El nombre de la foto es requerido</p>
          </div>
        </div>
         <div class="form-group" show-errors>
          <label class="control-label" for="image">URL</label>
          <input name="image" type="text" ng-model="vm.photo.image" id="image" class="form-control" placeholder="Url" required>
          <div ng-messages="vm.form.photoForm.image.$error" role="alert">
            <p class="help-block error-text" ng-message="required">La URL de la foto es requerido</p>
         </div>
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-default">{{vm.photo._id ? 'Update' : 'Crear'}}</button>
        </div>
        <div ng-show="vm.error" class="text-danger">
          <strong ng-bind="vm.error"></strong>
        </div>
      </fieldset>
    </form>
  </div>
</section>

1 个答案:

答案 0 :(得分:0)

使用此link并查看示例,因为

  

意思是'js'

使用

  

multer

在0.4.2上传已经集成,所以如果你想要你也可以从那里生成和复制并编辑一点点,因为它们不兼容