Hi everybody, maybe you had faced the same problem I had with nested Mongoose models in a Mongoose model.

I wanted to have, let’s say a comment object in my blog object. The problem I faced was, that I was not able to access the comment from the blog.

After some time, I got it. When you know it, it’s pretty easy 🙂 as everything..

 

So let’s start by creating the blog model, you can also create it by using the Mean.js generators (http://meanjs.org/generator.html).

You see, we have here a comment property where I am referencing the Objects Id of the comment model.

This property has to be saved to be able to get the comment model from the database. Of course, you can have it also as an array, but to keep it simple, let’s have just one comment in each blog.

 

Here is the comment model

To be able, to access the comment model from the blog model, you have to populate the comment model in the correct blog property, in our case it is the comment property.

See here (http://mongoosejs.com/docs/populate.html) for more information.

 

For that, we have the Blog Controller on server side with this two functions where we have to add the populate method.

Do you see that we added the .populate(‘comment’) in each of these functions? With this, you will be able to access the comment model from the blog model.

 

I will give you another tip. I faced also the problem that i tried to save the commentId at the wrong time.

You have to assign the commentId to the blog comment property in case of a successful creation of the comment within the callback like this (in AnuglarJS).

 

You will get the ID of the comment just from the response. Sure, here I am creating the Blog and comment at the same time. But this is just to show what I mean.

Enjoy coding 🙂

Populate nested objects with Mongoose in the MEAN Stack (MEAN.JS)
Tagged on:                 

4 thoughts on “Populate nested objects with Mongoose in the MEAN Stack (MEAN.JS)

  • April 14, 2015 at 7:51 pm
    Permalink

    Thank you for your very interesting post. I’m new to Mean.js. I have a problem when I try to make an array of comments. Do you have a few moments to explain to me how to do? thanks

    Sincerely Olivier

    Reply
    • June 11, 2015 at 12:21 pm
      Permalink

      Hi oliver,

      thanks for your comment.

      Ok, lets say you have a BlogSchema and a CommentSchema. What you have to do in your BlogSchema is, to add your CommentsSchema as an array, like this:

      comments: [{
      type: Schema.ObjectId,
      ref: 'Comments'
      }]

      Your full BlogSchema can look like this:


      'use strict';

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

      /**
      * Story Schema
      */
      var BlogSchema = new Schema({
      title: {
      type: String,
      default: '',
      required: 'Each good blog has a title'
      },
      content: {
      type: String,
      default:'',
      required: 'Each blog needs content'
      },
      comments: [{
      type: Schema.ObjectId,
      ref: 'Comments'
      }]
      });

      mongoose.model('Blog', BlogSchema)

      and your CommentsSchema like this:

      'use strict';

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

      /**
      * Story Schema
      */
      var CommentsSchema = new Schema({
      content: {
      type: String,
      default:'',
      required: 'Each comments needs content'
      }
      });

      mongoose.model('Comments', CommentsSchema)

      Hope this helps.

      Reply
      • February 1, 2016 at 1:49 pm
        Permalink

        Dear Damir,

        I need your help…And i hope you can help me…
        I tried to add an array of events in a employeSchema… The Schemas are ok.
        But when i’m check the reference id, the response is “null’. Do you know why ?

        If you had time…

        Here my $scope.create function
        —————-
        // Create new Employe object
        var employe = new Employes({
        name: this.name,
        evenements: $scope.addEvents(),// here the problem
        });
        // Redirect after save
        employe.$save(function (response) {
        $location.path(’employes/’ + response._id);
        }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
        });
        };

        Here the $scope.addEvents()
        ———
        $scope.addEvents = function(){
        var start, end, repet, hours, minutes, evenement;
        for (var i = 0; i<$scope.days.length; i++){
        if ($scope.days[i].work===true){
        evenement = $scope.createEvent(
        start='2016-01-08',
        end= '2016-01-10',
        );
        $scope.eventIds.push(evenement);
        }
        }
        return $scope.eventIds;
        };

        Here the createEvent()
        ———-
        $scope.createEvent = function (start, end){
        var id;
        var evenement = new Evenements({
        typeEvenement:'Présence',
        start: start,
        end: end,
        });
        // Redirect after save
        evenement.$save(function (response) {
        id = response._id;
        }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
        });
        return evenement;
        };

        Reply
        • February 11, 2016 at 5:41 pm
          Permalink

          Hi Olivier,

          hmm.. very strange. Actually, how it looks for me, this should work how you did it.. did you check that your object is saved to the DB?
          and what else you have in the response object?

          Reply

Leave a Reply

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: