Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I have a problem with getting nested objects in a model. I have a model restaurant, where i am referencing an article. This is just an demo for me to test how this is working, but i am not getting it.. :(

ah.. i am using meanjs..

here is my restaurant model..

'use strict';

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

/**
 * Restaurant Schema
 */
var RestaurantSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Restaurant name',
        trim: true
    },
    desc: {
        type: String,
        default: 'description is here'
    },
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    article: {
        type: Schema.ObjectId,
        ref: 'Article'
    }
});

mongoose.model('Restaurant', RestaurantSchema);

This is my Article model.

'use strict';

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

/**
 * Article Schema
 */
var ArticleSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true,
        required: 'Title cannot be blank'
    },
    content: {
        type: String,
        default: '',
        trim: true
    }
});

mongoose.model('Article', ArticleSchema);

this two methods are in the nodejs backend restaurant controller:

exports.list = function(req, res) { Restaurant.find().sort('-created').populate('article').exec(function(err, restaurants) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(restaurants);
        }
    });
};

exports.restaurantByID = function(req, res, next, id) { Restaurant.findById(id).populate('article').exec(function(err, restaurant) {
        if (err) return next(err);
        if (! restaurant) return next(new Error('Failed to load Restaurant ' + id));
        req.restaurant = restaurant ;
        next();
    });
};

I have then an angular controller method to safe a new restaurant and an article, which is working. When i am accessing "http://localhost:3000/#!/articles". But when i am trying to get for example the title out, it is not working.

I am creating my restaurant and article this way:

// Create new Restaurant
        $scope.create = function () {
            // Create new Restaurant object

            var newArticle = new Articles({
                title: this.articleTitle
            });
            newArticle.$save();

            var restaurant = new Restaurants({
                name: this.name,
                desc: this.description,
                article: newArticle._id
            });

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

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

this is in my create view:

<div class="controls">
                        <input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>
                        <input type="text" data-ng-model="articleTitle" id="article" class="form-control" placeholder="artikel" required>
                        <input type="text" data-ng-model="description" id="description" class="form-control" placeholder="desription" required>
                    </div>

and this is in my list view

<h4 class="list-group-item-heading" data-ng-bind="restaurant.name"></h4>
            <h3 class="list-group-item-heading" data-ng-bind="restaurant.article"></h3>
            <h3 class="list-group-item-heading" data-ng-bind="restaurant.desc"></h3>

the description is visible in the browser, but, nothing visible about the article. How do i get the information about the article in the restaurant object?

Probably, this is very easy, but i did not find it out..

thanks in advanced..

share|improve this question
    
The interresting thing is also that i am not getting the id of the article either.. – damir Oct 8 '14 at 15:50

1 Answer 1

up vote 0 down vote accepted

so i figured it out.. i made a mistake of how i am creating the article. I thougt maybe it was something wrong with article, then i created a new crud dish..

first, i am saving the dish, and in the callback i am creating the restaurant with the information i got from the callback response.. this worked for me..

// Create new Restaurant
        $scope.create = function () {
            // Create new Restaurant object

            var dishId = 0;
            var thisObject = this;

            var newDish = new Dishes({
                name: this.dishName
            });
            newDish.$save(function(response){
                    console.log('XX in $save: %s', response._id);
                    dishId = response._id;

                    var restaurant = new Restaurants({
                        name: thisObject.name,
                        desc: thisObject.description,
                        art: {
                            title: thisObject.artTitle,
                            content: thisObject.artContent
                        },
                        dish: dishId
                    });

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

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

and of course, i have to populate this new dish in my server controller:

exports.list = function(req, res) { Restaurant.find().sort('-created').populate('dish').exec(function(err, restaurants) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(restaurants);
        }
    });
};

exports.restaurantByID = function(req, res, next, id) { Restaurant.findById(id).populate('dish').exec(function(err, restaurant) {
        if (err) return next(err);
        if (! restaurant) return next(new Error('Failed to load Restaurant ' + id));
        req.restaurant = restaurant ;
        next();
    });
};

and this is my restaurant model:

    'use strict';

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

    /**
     * Restaurant Schema
     */

var RestaurantSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Restaurant name',
        trim: true
    },
    desc: {
        type: String,
        default: 'description is here'
    },
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    article: {
        type: Schema.ObjectId,
        ref: 'Article'
    },
    dish: {
        type: Schema.ObjectId,
        ref: 'Dish'
    },
    art: {
        title: {
            type: String,
            default: 'HelloTitle',
            trim: true,
            required: 'Title cannot be blank'
        },
        content: {
            type: String,
            default: '',
            trim: true
        }
    }
});

mongoose.model('Restaurant', RestaurantSchema);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.