L
L
likejavascript2014-05-19 14:30:23
MongoDB
likejavascript, 2014-05-19 14:30:23

How to group documents in MongoDB/mongoose?

There is the following model structure:

//Unit.js
    
var mongoose = require('mongoose');
module.exports = mongoose.model('Unit', new mongoose.Schema({
   title: {type: String},
   _folder: {type: mongoose.Schema.Types.ObjectId, ref: 'Folder'}
}));   

//Folder.js

var mongoose = require('mongoose');
module.exports = mongoose.model('Folder', new mongoose.Schema({
   title: {type: String}
}));   

//Document.js
    
var mongoose = require('mongoose');
module.exports = mongoose.model('Document', new mongoose.Schema({
   title: {type: String},
   folders: [{type: mongoose.Schema.Types.ObjectId, ref: 'Folder'}]
}));

Each document contains an array of folders (folders).
There are units (elements), each of which belongs to a specific folder and is linked by _folder. I need to request a document by _id and get all its folders and events. Settled on this:
app.get('/document/:id', function(req, res, next) {
        return Document.findOneById(req.params.id)
            .populate('folders')
            .exec(function (err, document) {
                if (err) return next(err);
                // здесь нужно наполнить массив document.folders соответствующими элементами (units)
            });
});

Help us complete the request, we need to fill the document.folders array with the appropriate elements (units). I understand that you need to use aggregate, but I don’t understand how to correctly compose a query in order to eventually get this document:
{
       _id: ObjectId(...),
       title: 'Document title',
       folders: [
          {
             _id: ObjectId(...),
             units: [
                {
                   _id: ObjectId(...),
                   title: 'Unit title'
                }
             ]
          }
       ]
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question