Search code examples
node.jsapostrophe-cms

Why is the apostrophe-pages _children array is always empty?


I am trying to get the children of apostrophe pages to appear in my navigation object - however the _children array is always empty. My page does have child pages set up via the front end Pages UI.

My index.js for the lib/modules/apostrophe-pages module contains the following:

  construct: function(self,options) {
      // store the superclass method and call at the end
      var superPageBeforeSend = self.pageBeforeSend;
      self.pageBeforeSend = function(req, callback) {

    // Query all pages with top_menu setting = true and add to menu collection
    self.apos.pages.find(req, { top_menu: true }, {slug: 1, type: 1, _id: 1, title: 1})
       .children(true)
       .toArray(
           function (err, docs) {  
              if (err) {
                 return callback(err);
              }
              req.data.navpages = docs;
              return superPageBeforeSend(req, callback);
           });
    };

  },   
...

My top_menu attribute is set via apostrophe-custom-pages:

module.exports = {
  beforeConstruct: function(self, options) {
    options.addFields = [
      {
        name: 'subtitle',
        label: 'Subtitle',
        type: 'string'
      },
      {
        name: 'css_class',
        label: 'CSS Class',
        type: 'string'
      },
      {
        name: 'top_menu', 
        label: 'Include In Top Menu',
        type: 'boolean'
      }
    ].concat(options.addFields || []);
   }
};

This gives me the pages I need with the top_menu setting.. but I want to get child pages too..

When debugging the code I can see that the docs._children array is present but is always empty, even though a page has child pages...

I have tried adding the following both to my app.js and to my index.js but it doesn't change the result:

  filters: {
    // Grab our ancestor pages, with two levels of subpages
    ancestors: {
      children: {
        depth: 2
      }
    },
    // We usually want children of the current page, too
    children: true
  }

How can I get my find() query to actually include the child pages?


Solution

  • Solved it..

    I needed to add 'rank: 1, path: 1, level: 1' to the projection as per this page in the documentation: https://apostrophecms.org/docs/tutorials/howtos/children-and-joins.html#projections-and-children