Pregunta

I'm beginning to use restangular for the first time and struggling to access nested documents. If I have a Mongoose schema like so:

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');
};

To access and employee within a department, I thought I could simply do the following:

        var getEmployeeById = function(departmentId, empId) {

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

Although I can retrieve a department, and when I do, it has a nested employees array, correctly populated with the employees I expect. I can't actually retrieve an individual employee via its id as I intended. I end up with a 404.

What am I doing wrong?

¿Fue útil?

Solución

I'm the creator of Restangular.

I don't know 100% how Mongose works with Express or with what you're exposing the API but the idea is that you should have some nested Restful Resources as well as this "nesting" in your mongo documents.

So, you should have some Rest API that given a request to /departments/123 returns the department 123 and that given /departments/123/employees/456 returns the employee 456 of the department 123. If you have a Rest API for that, then, you're going to get the rigth response with Restangular :D

Hope this works for you!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top