Search code examples
reactjsmongodbmeteorgraphqlapollo

Sorting MongoDB data in GraphQL resolver (Meteor/React/Apollo)


I'm trying to sort some data returned by a query in GraphQl. I'm running a Meteor/React/Apollo/Graphql stack, and this line allows me to obtain all the data in my database in a resolver resolvers.js : return database.find({}) I would like to sort it server-side by the "name" field and according to the docs and everything else I've been able to find online so far, return database.find({}).sort({name:1}) should have cut it, but it's not actually returning anything and I can't seem to figure out why, nothing shows up in my console and no errors are being thrown, and hence I believe it's just null or empty.

In my Robo3T console I can run database.find({}).sort({name:1}) and I can see the data actually being sorted. According to the docs I thought it may have been due to the Node implementation, and so I tried sort([["name",1]]) but that did not work either, and I'm not quite sure how else to go about this.

If there is no way to do this - should I just rely on client-side sorting? It's not many entries, < 100, and I think I should just sort it in the database itself because I never need the unsorted data and it's likely not even going to change much.

I would like to ask this regardless though, even if just sorting it once in my database is enough for this specific situation, how would I otherwise go about sorting data in a resolver, because I would need to do this in other instances?

Thanks!

EDIT - This is what I have:

export default {
    Query: {
        test_query(obj, args, context) {
            // Bottom line is output
            console.log("test1");
            console.log(Database.find({}).sort({name:1}));
            // Bottom line is not output
            console.log("test2");
            return Database.find({});
        },
}

EDIT2: My database is defined as Database = new Mongo.Collection("db_name")


Solution

  • I believe you are looking at the wrong documentation. If this is indeed meteor, then Database is presumably a meteor collection, not a raw mongo collection. The interface on meteor collections is slightly different. In your case, I think you want:

    Database.find({}, {sort: {name: 1}}).fetch();