无法使用Angular

时间:2015-10-22 23:04:47

标签: javascript angularjs node.js mongodb mean-stack

我是MEAN Stack的新手,刚刚完成了本教程:http://www.bradoncode.com/tutorials/learn-mean-stack-tutorial/

我有两个使用Mongoose设置的mongoDB模式 - 用户和发票。一个有一个现场国家,另一个有一个现场公司,两个都包含一个字符串,即国家的名称。创建帐户的所有用户都有不同的公司(国家/地区)。目标是显示的发票应仅适用于用户所属的公司(国家/地区)。因此,如果用户来自澳大利亚,他应该只看到发送到澳大利亚的发票。 问题是它们是两种不同模式的一部分。这是发票架构:

'use strict';

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

/**
 * Invoices Schema
 */
var InvoiceSchema = new Schema({
    invoice_date: {
        type: Date,
        default: Date.now
    },
    from_entity: {
        type: String,
        default: '',
        trim: true,
        /*required: 'service line cannot be blank'*/
    },
    from_service: {
        type: String,
        default: '',
        trim: true,     
        /*required: 'service line cannot be blank'*/
    },

    country: {
        type: String,
        default: '',
        trim: true,
        /*required: 'service line cannot be blank'*/
    },

    to_entity: {
        type: String,
        default: '',
        trim: true,
        /*required: 'service line cannot be blank'*/
    },

    to_service: {
        type: String,
        default: '',
        trim: true,     
        /*required: 'service line cannot be blank'*/

    },

    partner: {
        type: String,
        default: '',
        trim: true  
        /*required: 'partner cannot be blank'*/
    },

    invoice_number: {
        type: String,
        default: '',
        trim: true,     
        unique: true
    },

    currency: {
        type: String,
        default: '',
        trim: true,
        /*required: 'currency cannot be blank'*/
    },


    amount: {
        type: Number,
        default: '',
        trim: true,
        /*required: 'amount cannot be blank'*/
    }, 

    user: {
    type: Schema.ObjectId,
    ref: 'User'
}
});

mongoose.model('Invoice', InvoiceSchema);

以下是用户架构:

'use strict';

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

/**
 * A Validation function for local strategy properties
 */
var validateLocalStrategyProperty = function(property) {
    return ((this.provider !== 'local' && !this.updated) || property.length);
};

/**
 * A Validation function for local strategy password
 */
var validateLocalStrategyPassword = function(password) {
    return (this.provider !== 'local' || (password && password.length > 6));
};

/**
 * User Schema
 */
var UserSchema = new Schema({
    firstName: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your first name']
    },
    lastName: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your last name']
    },
    displayName: {
        type: String,
        trim: true
    },
    email: {
        type: String,
        trim: true,
        default: '',
        validate: [validateLocalStrategyProperty, 'Please fill in your email'],
        match: [/.+\@.+\..+/, 'Please fill a valid email address']
    },
    username: {
        type: String,
        unique: 'testing error message',
        required: 'Please fill in a username',
        trim: true
    },
    password: {
        type: String,
        default: '',
        validate: [validateLocalStrategyPassword, 'Password should be longer']
    },
    salt: {
        type: String
    },
    provider: {
        type: String,
        required: 'Provider is required'
    },
    providerData: {},
    additionalProvidersData: {},
    roles: {
        type: [{
            type: String,
            enum: ['Canada', 'Australia']
        }],
        default: ['Canada']
    },
    updated: {
        type: Date
    },
    created: {
        type: Date,
        default: Date.now
    },
    /* For reset password */
    resetPasswordToken: {
        type: String
    },
    resetPasswordExpires: {
        type: Date
    },
    firm: {
        type: String,
        trim: true,
        default: 'Canada'
    }
});

/**
 * Hook a pre save method to hash the password
 */
UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});

/**
 * Create instance method for hashing a password
 */
UserSchema.methods.hashPassword = function(password) {
    if (this.salt && password) {
        return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
    } else {
        return password;
    }
};

/**
 * Create instance method for authenticating user
 */
UserSchema.methods.authenticate = function(password) {
    return this.password === this.hashPassword(password);
};

/**
 * Find possible not used username
 */
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
    var _this = this;
    var possibleUsername = username + (suffix || '');

    _this.findOne({
        username: possibleUsername
    }, function(err, user) {
        if (!err) {
            if (!user) {
                callback(possibleUsername);
            } else {
                return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
            }
        } else {
            callback(null);
        }
    });
};

mongoose.model('User', UserSchema);

这是我的invoices.server.controller:

        'use strict';

        /**
         * Module dependencies.
         */
        var mongoose = require('mongoose'),
          errorHandler = require('./errors.server.controller'),
          User = mongoose.model('User'),
          Invoice = mongoose.model('Invoice'),
            _ = require('lodash');

        var crud = require('./crud.server.controller')('Invoice', 'invoice_number');

        module.exports = crud;

    Here is my invoice.client.controller:

'use strict';

// Invoices controller
angular.module('invoices').controller('InvoicesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Invoices', 'Users', '$filter',
    function($scope, $stateParams, $location, Authentication, Invoices, Users, $filter) {
        $scope.authentication = Authentication;
        $scope.users = Users.query();
        $scope.currentPage = 1;
        $scope.pageSize = 10;
        $scope.offset = 0;

        // Page changed handler
        $scope.pageChanged = function() {
            $scope.offset = ($scope.currentPage - 1) * $scope.pageSize;
        };

        // Create new Invoice
        $scope.create = function() {
            var invoice = new Invoices ({
                    amount: this.amount,
                    invoice_number: this.invoice_number,
                    partner: this.partner,
                    to_service: this.to_service,
                    to_entity: this.to_entity,
                    country: this.country,
                    from_service: this.from_service,
                    from_entity: this.from_entity
            });

            // Redirect after save
            invoice.$save(function(response) {
                $location.path('invoices/' + response._id);

                // Clear form fields
                $scope.name = '';
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

        // Remove existing Invoice
        $scope.remove = function(invoice) {
            if (invoice) {
                invoice.$remove();

                for (var i in $scope.invoices) {
                    if ($scope.invoices [i] === invoice) {
                        $scope.invoices.splice(i, 1);
                    }
                }
            } else {
                $scope.invoice.$remove(function() {
                    $location.path('invoices');
                });
            }
        };

        // Update existing Invoice
        $scope.update = function() {
            var invoice = $scope.invoice;

            invoice.$update(function() {
                $location.path('invoices/' + invoice._id);
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

// MY CODE
        var findInvoice = function findInvoice(p) {
            // You could substitue use of filter here with underscore etc.
            p.user = $filter('filter')($scope.users, {firm : Invoices.country});
        };

        // Find a list of Invoices
        $scope.find = function() {
                    $scope.invoices = Invoices.query(function countryInvoices (invoices) {
                    invoices.forEach(findInvoice);
                    $scope.invoices = invoices;
                });
            };


        // Find existing Invoice
        $scope.findOne = function() {
            $scope.invoice = Invoices.get({ 
                invoiceId: $stateParams.invoiceId
            });
        };


        // Search for a Invoice
        $scope.invoiceSearch = function(invoice) {
            $location.path('invoices/' + invoice._id);
        };
    }
]);

正如你可以看到下面的图片,中国出现在那里,但不应该因为用户从加拿大登录。

enter image description here

帮助将不胜感激。如果故障排除需要发布更多代码,请告知我们。

1 个答案:

答案 0 :(得分:0)

您将发送一个请求,以某种方式包含您的用户对象的国家/地区部分。

最终看起来像这样:

在控制器中:

$scope.user = Auth.getCurentUser();

invoiceAPI.getUserInvoices($scope.user.country)
  .then(function(data) {
    $scope.userInvoices = data;
  });

服务是:

function getUserInvoices(id) {
  var url = '/api/invoice/?country=' + id;
  var request = $http.get(url, {
    cache: true
  });
  return (request.then(handleSuccess, handleError));
}

服务器控制器是:

 exports.userInvoices = function(req, res) {
  Invoice.find({
    country: {
      $in: req.query.country
    }
  })
  .exec(function(err, looks) {
    if (err) {
      return handleError(res, err);
    }
    console.log(looks);
    return res.status(200)
      .json(looks);
  });
};