mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

sort of populate with nested populate not working

Open leanpilar opened this issue 8 years ago • 8 comments

this works:

Model.find({})
  .populate({path: 'firstChild', options: {sort: {position: -1}}})

this works:

Model.find({})
  .populate({path: 'firstChild', populate: {path: 'secondChild' }})

but combined don't

Model.find({})
  .populate({path: 'firstChild', options: {sort: {position: -1}}, populate: {path: 'secondChild' }})

All 3 version doesn't throw an error, in all 3 version the populate is correct, but in the 3rd it doesen't sort

leanpilar avatar Oct 01 '18 12:10 leanpilar

@leanpilar It's worth noting that sorting in populate has been precarious in the past, enough so, to be mentioned in the FAQ. I created the following example to try and replicate what you're seeing, but it works as expected. Can you edit the script so that it fails in the way you're seeing, or create a complete script like it that does?

7072.js

#!/usr/bin/env node
'use strict';

const assert = require('assert');
const mongoose = require('mongoose');
const { Schema, connection} = mongoose;
const GH = 'gh7072';
const URI = `mongodb://localhost:27017/${GH}`;
const OPTS = { family: 4, useNewUrlParser: true };

const aSchema = new Schema({
  name: String,
  firstChild: [{
    type: Schema.Types.ObjectId,
    ref: 'b'
  }]
});

const bSchema = new Schema({
  name: String,
  position: Number,
  secondChild: {
    type: Schema.Types.ObjectId,
    ref: 'c'
  }
});

const cSchema = new Schema({
  name: String
});

const A = mongoose.model('a', aSchema);
const B = mongoose.model('b', bSchema);
const C = mongoose.model('c', cSchema);

const bs = [];
const cs = [];
const bnames = [];
const bpositions = [];
const cnames = [];

for (let i = 0; i < 100; i++) {
  const c = new C({ name: `c${i}`});
  const b = new B({ name: `b${i}`, secondChild: c._id, position: i });
  cnames.unshift(c.name);
  bnames.unshift(b.name);
  bpositions.unshift(i);
  bs.push(b);
  cs.push(c);
}

const a = new A({ name: 'a1', firstChild: bs.map(d => d._id) });

async function run() {
  await mongoose.connect(URI, OPTS);
  await connection.dropDatabase();
  await A.create(a);
  await B.create(bs);
  await C.create(cs);
  const popObj = {
    path: 'firstChild',
    options: { sort: { position: -1 } },
    populate: {
      path: 'secondChild'
    }
  };
  const docs = await A.find({}).populate(popObj);
  const doc = docs[0];
  assert.deepStrictEqual(doc.firstChild.map(d => d.name), bnames);
  assert.deepStrictEqual(doc.firstChild.map(d => d.position), bpositions);
  assert.deepStrictEqual(doc.firstChild.map(d => d.secondChild.name), cnames);
  console.log('All Assertions Pass.');
  await connection.close();
}

run();

Output:

issues: ./7072.js
All Assertions Pass.
issues:

ghost avatar Oct 01 '18 14:10 ghost

I'm googled for 2 days and I found as you mentioned a lot of sort problems... And because all my normal sort works I think that a lot of that I read it was fixed... more difficult is that Englis is my second foreign language so, I'll try again :D

in my collection, I have a field called position of type number not in order

calling

Model.find({})
  .populate({path: 'childList', options: {sort: {position: 1}}})

will sort correctly and output:

[ {
childList: [
  {position: 1,'id'....}
  {position: 2,'id'....}
  {position: 3,'id'....}
  {position: 4,'id'....}
]},{},]

if I add a nested(populate of populate) option the my code it stop sorting

Model.find({})
  .populate({path: 'childList', options: {sort: {position: -1}}, populate: {path: 'secondChild' }})
[ {
childList: [
  {position: 3,{_id:'}....}
  {position: 4,{_id:'}....}
  {position: 1,{_id:'}....}
  {position: 2,{_id:'}....}
]},{},]

the long code:

parent schema: here a normal .sort() function forks as expected but removed for debugging

const parentSchema = Schema({
   ....
    childList: [{     <- child
        type: Schema.Types.ObjectId,
        ref: 'Clild'
    }],
});

first child: where I want to sort

const childSchema = Schema({
   ....
    secondChild: {
        type: Schema.Types.ObjectId,
        ref: 'ChildCat'
    },
    position: {
        type: Number,
    },
   ....
});

second child:

const childCatSchema = Schema({
   ...
    category: {
        type: String,
        required: true,
        unique: true
    },
   ...
});

my complete function for this example, not translated is:

    const allSort = {};
    UpravaGrupa.find({} )
        .populate({path: 'upravaList', options: {sort: {'position': 1}}, populate: {path: 'pozicija'}})
        .sort({position: -1})
        .exec((err, nested) => {
            if (err) return res.status(400).json({status: 'error', message: err.message});
            allSort.nested = nested;
            UpravaGrupa.find({} )
                .populate({path: 'upravaList', options: {sort: {'position': 1}}})
                .sort({position: -1})
                .exec((err, notnested) => {
                    if (err) return res.status(400).json({status: 'error', message: err.message});
                    allSort.notNested = notnested;
                    return res.status(200).json(allSort)
                });
        });

the result in console you can find here: https://goo.gl/6jxp4R I try to rename the sort field in parent and firstChild because there are the same name, but the result is the same. the only plugin used is mongoose-slug-generator, no others like pre or post in schema.

leanpilar avatar Oct 01 '18 16:10 leanpilar

@leanpilar in your not translated example, you're applying the query helper .sort({ position: -1 }) to the UpravaGrupa query,

does UpravaGrupa have a position field as well as upravaList?

That .sort() will apply to the initial find on UpravaGrupa, not to the populated docs returned after .populate().

ghost avatar Oct 01 '18 21:10 ghost

yes, both parent and first child have a field named 'position' and both of them are sorted as I want, until I add the populate for the second child. adding: populate: {path: 'pozicija'}, then the sort of the first child fail, but the query sort() on parent works. for testing, I removed the sort() on the parent, and renamed the field on the parent, but the result is the same. Today I notice that the position value of the first child was not not 1,2,3 but 12, 7, 19 and try to set manually 1,2,3 but nesting the second child, the sort of the child has the same wrong behaviour.

leanpilar avatar Oct 02 '18 12:10 leanpilar

@leanpilar I've got the data from the console you pointed to, can you share all of your actual schema for this and I'll use them to try and reproduce this.

ghost avatar Oct 02 '18 13:10 ghost

ok, let's try

const upravaGrupaSchema = Schema({
    grupa: {
        type: String,
        required: true,
        unique: true
    },
    note: {
        type: String,
    },
    position: {
        type: Number,
    },
    upravaList: [{
        type: Schema.Types.ObjectId,
        ref: 'Uprava'
    }],
});
const upravaSchema = Schema({
    ime: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    pozicija: {
        type: Schema.Types.ObjectId,
        ref: 'UpravaCat'
    },
    grupa: {
        type: Schema.Types.ObjectId,
        ref: 'UpravaGrupa'
    },
    slug: {
        type: String,
        slug: "ime"
    },
    position: {
        type: Number,
    },
    body: {
        type: String,
        required: true,
    },
    photo: {
        type: String,
        required: true,
        trim: true
    },
    facebook: {
        type: String,
    },
    twitter: {
        type: String,
    },
    google: {
        type: String,
    },
    instagram: {
        type: String,
    },
    address: {
        type: String,
    },
    phone: {
        type: String,
    },
    email: {
        type: String,
    },
    stranka: {
        type: String,
    },
});
const upravaCatSchema = Schema({
    category: {
        type: String,
        required: true,
        unique: true
    },
});

the router call is the same

leanpilar avatar Oct 02 '18 14:10 leanpilar

found the problem... Today after I boot my pc the sort it starts working and I start investigating... after I upgrade the mongoose to the last version I needed to restart mongodb.

the same on my ubuntu-nginx-pm2 server

service mongodb restart

and now it works like it has to.

leanpilar avatar Oct 03 '18 08:10 leanpilar

@leanpilar that's perplexing, but I'm glad you got it sorted out.

ghost avatar Oct 03 '18 12:10 ghost