【问题标题】:How to access nested documents using Restangular如何使用 Restangular 访问嵌套文档
【发布时间】:2013-06-12 14:58:39
【问题描述】:

我第一次开始使用restangular,并且难以访问嵌套文档。如果我有这样的 Mongoose 架构:

var mongoose = require('mongoose');

module.exports = function Schemas() {
    this.schema = mongoose.Schema;

this.EmployeeSchema = new this.schema({
    'firstname': {
        type: String,
        required: true,
        trim: true
    },
    'lastname': {
        type: String,
        required: true,
        trim: true
    },
    'email': {
        type: String,
        required: true,
        trim: true,
        index: true,
        validate: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/
    },
    'departmentId': {
        type: this.schema.ObjectId,
        trim: true,
        required: true
    },
    'enddate': {
        type: String,
        trim: true
    },
    'active': {
        type: Boolean,
        "default": true
    }
});
this.EmployeeSchemaModel = mongoose.model('employees', this.EmployeeSchema);

this.DepartmentSchema = new this.schema({
    'name': {
        type: String,
        required: true,
        trim: true,
        index: {
            unique: true
        }
    },
    'employees': [this.EmployeeSchema]
});
    this.DepartmentSchemaModel = mongoose.model('departments', this.DepartmentSchema);
    mongoose.connect('mongodb://localhost:8120/staff');
};

要访问部门内的员工,我想我可以简单地执行以下操作:

        var getEmployeeById = function(departmentId, empId) {

             Restangular.one('departments',departmentId).one('employees', empId).get().then(function (emp){
            return emp;
        });

虽然我可以检索一个部门,但当我这样做时,它有一个嵌套的雇员数组,正确地填充了我期望的雇员。我实际上无法按照我的意图通过其 id 检索单个员工。我最终得到了 404。

我做错了什么?

【问题讨论】:

    标签: angularjs mongoose restangular


    【解决方案1】:

    我是 Restangular 的创造者。

    我不知道 100% Mongose 如何与 Express 或您公开的 API 一起工作,但想法是您应该在您的 mongo 文档中拥有一些嵌套的 Restful 资源以及这种“嵌套”。

    因此,您应该有一些 Rest API,向 /departments/123 发出请求会返回部门 123,而给定 /departments/123/employees/456 会返回部门 123 的员工 456。如果您有 Rest API那么,为此,您将使用 Restangular 获得正确的响应:D

    希望这对你有用!

    【讨论】:

    • 感谢您的回复。经过一番研究,我正在考虑使用 MERS (github.com/jspears/mers),它允许您结合 Mongo、Express 等来开发 RESTful 后端。从我目前所能收集到的信息来看,我认为 Restangular 可以很好地使用它。顺便说一句,Restangular 做得很好,它对开箱即用的 ngResource 进行了巨大改进。
    • 嘿,我知道很多使用 Restangular 的人实际上在使用 MERS 没有任何问题 :)
    猜你喜欢
    • 1970-01-01
    • 2018-09-19
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多