Can't get sort to work in aggregate query

Here’s my code pulling NTFs from the database, but ‘sort’ doesn’t work, tried many things. Is there something wrong with my syntax?

// get user items
Moralis.Cloud.define('getUserItems', async (request) => {
  const pipeline = [
    {
      match: {
        contract_type: 'ERC721',
        token_address: request.params.tokenAddress,
        owner_of: { $in: request.params.forUserAddress ? request.params.forUserAddress : request.user.attributes.accounts },
      }, 
    },
    {
      lookup: {
        from: 'ItemsForSale'+request.params.network,
        localField: "token_id",
        foreignField: "tokenId",
        as: "marketItem"
      }
    },
    { sort : { createdAt: -1 } },
  ]
  const query = new Moralis.Query(request.params.network+'NFTOwners')
  return query.aggregate(pipeline)
},{
  fields : ['network', 'tokenAddress'],
  requireUser: true
})

Changing anything to sort, using other fields, nothing changes, always sorting the same.

1 Like

Hey @matiyin

There is a problem with $in:

owner_of: { $in: [request.params.forUserAddress ? request.params.forUserAddress : request.user.attributes.accounts] },

I’ve tried your code and there is a problem with sorting by “createdAt” because in my case it has string type I don’t know why, because in the database it has Date.

Try again please with code fix :man_mechanic:

1 Like

And let me know how it will work. Also you can create additional column for example: “itemAddedOnMarket” and pass to it values from “createdAt” :sweat_smile:

1 Like

@Yomoo

thanks for checking and nonstop help!

Indeed sorting doesn’t work on createdAt with this pipeline format, but it does work when I use query.descending(‘createdAt’) in another query.
Very strange! Indeed in the db createdAt is Date type…how do you see it outputs a string?

Anyway, for a workaround I’ve now used block_number, which works fine since it’s a Number type.
I could not use token_id since this is String type. I know there’s a way to interpret Strings as Numbers in mongo but I cant find the right syntax for it, do you know?

Hey @matiyin

This is a good idea to use block_number :muscle:
Just wanted to write about it :sweat_smile:

Unfortunately I can’t find informartion why doest this happen. For example you can aggreggate and then sort info by created_at but before you need to parse the date.

:man_mechanic:

using _created_at in a pipeline instead of createdAt does the trick and works

1 Like

Life saver! Thanks so much!

1 Like