如何使用 Restangular 访问嵌套文档

Posted

技术标签:

【中文标题】如何使用 Restangular 访问嵌套文档【英文标题】:How to access nested documents using 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。

我做错了什么?

【问题讨论】:

【参考方案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 没有任何问题 :)

以上是关于如何使用 Restangular 访问嵌套文档的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AngularJS 和 Restangular 返回/编辑 REST 资源

如何使用 AngularJS 和 Restangular 返回/编辑 REST 资源

如何使用 httpbackend 测试 Restangular http 调用以测试成功和错误情况?

setFullResponse(true) 时没有自定义标题

如何访问 MongoDB 中的嵌套数组?

当嵌套字典键发生变化时,如何使用嵌套字典查询 mongodb 文档?