Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

Filter, sort, limit, skip subdocument mongoose


const A = mongoose.Schema({
...
    bs: [B.schema],
...

 });

So basically i have two schemas, and one is subdocument of another. From my datatable i get params. like filter, page limit, page, sort...

What i need to do is, to create query that will with _id from A schema get all his B schemas and always sort, limit, skip, filter with params. that i sent

I tried something like this

b = await A.find({'_id' : idA}, 
    { 'bs' : 
        { $slice: [ offset * limit, limit ]
        }
    }); 

And it's working but i can't still figure out how to filter and sort. So if somebody have some idea welcome to share.

P.S Sorry for bad english Regards, Salesh


Solution

  • What you're trying to do is not find A documents that fulfill your array criteria, but to modify the results to accommodate to your needs. You can do this with two approaches, depending on where you want the processing to be done:

    1. Use MongoDB Aggregation. The processing is done in the DB.

    The aggregation pipeline is a series of steps you determine that documents go through being queried and transformed. A rough untested (and probably syntactically wrong) example would be:

    A.aggregate([
      { $match: { _id: "id" }},
      { $project: {
          bs: {
            $filter: { input: "$bs" , as: "filteredBs" , cond: { /* conditions object */}  }},
         } 
      },    
      { $slice: ["$filteredBs", offset * limit, limit ] }
      /* ... */
    ]);
    

    2. Get the document by Id and process the array on your server.

    Here you're just limited by javascript and its array capabilites.

    const found = A.findById('id');
    const bs = A.bs.filter( /* filter function */ ).slice() // ... whatever you want.
    A.bs = bs;
    return A;