question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Filtering and search by ID does not work

See original GitHub issue

Describe the bug Filtering and search by ID does not work. As far as I understand, @admin-bro/mongoose has wrong cast of type ObjectId. There is no id in property types and @admin-bro/mongoose converts ObjectId to string. As a result, a regular expression string filter is obtained

Error

[Node] 2021-01-14 19:38:43 error: Error: Can't use $options [Node] at ObjectId.SchemaType.castForQuery (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/schematype.js:1495:13) [Node] at ObjectId.SchemaType.castForQueryWrapper (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/schematype.js:1467:22) [Node] at cast (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/cast.js:310:39) [Node] at model.Query.Query.cast (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/query.js:4786:12) [Node] at model.Query.Query._castConditions (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/query.js:1874:10) [Node] at model.Query.<anonymous> (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/query.js:1901:8) [Node] at model.Query._wrappedThunk [as _find] (/home/doss/Projects/fitnes-batut/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8) [Node] at /home/doss/Projects/fitnes-batut/node_modules/kareem/index.js:369:33 [Node] at processTicksAndRejections (internal/process/task_queues.js:79:11)

Installed libraries and their versions

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:8
  • Comments:7

github_iconTop GitHub Comments

1reaction
alecgibsoncommented, Feb 17, 2022

@Gadana1 's solution involves copy-pasting code out of the adminjs codebase, which is pretty fragile. At any rate, I did more digging and the issue is actually with @adminjs/mongoose. Somebody actually raised a PR to fix this in December, which has been approved but not merged: https://github.com/SoftwareBrothers/adminjs-mongoose/pull/39

Any chance we can get that merged and released?

1reaction
Gadana1commented, Aug 13, 2021

The only way I could solve this was to ad a global list action. So if _id is passed then I get the item by id else, proceed with the normal flow.

// global.js


  const { SortSetter, Filter, populator } = require('adminjs');
  const AdminJS = require('adminjs');
  const flat = require('flat');
  
  // Max records for each page
  const PER_PAGE_LIMIT = 100;
  
  const Action = {
      /**
       * @param {AdminJS.ActionRequest} request
       * @param {AdminJS.ActionResponse} response
       * @param {AdminJS.ActionContext} context
       * @returns {AdminJS.ListActionResponse} context
       */
      list: async (request, response, context) => {
          const { query } = request;
          const { sortBy, direction, filters = {} } = flat.unflatten(query || {});
          const { resource } = context;
  
          let { page = 1, perPage = 10 } = flat.unflatten(query || {});
          perPage = +perPage > PER_PAGE_LIMIT ? PER_PAGE_LIMIT : +perPage;
  
          const listProperties = resource.decorate().getListProperties();
          const firstProperty = listProperties.find((p) => p.isSortable());
          const sort = firstProperty ? SortSetter({ sortBy, direction }, firstProperty.name(), resource.decorate().options) : null;
  
          /** @type {AdminJS.BaseRecord[]} */
          let records = [];
          let total = 0;
  
          // If filter by ID passed, then get item by ID
          if(filters._id) {
            records = await resource.findMany([filters._id]);
            total = records ? records.length : 0;
          }
  
          // Search and filter if id not passed
          else {
            const filter = await new Filter(filters, resource).populate();
            records = await resource.find(filter, {
                limit: perPage,
                offset: (page - 1) * perPage,
                sort,
            });
            total = await resource.count(filter);
          }
  
          const populatedRecords = (context.records = await populator(records));
          return {
              meta: {
                  total,
                  perPage,
                  page,
                  direction: sort.direction,
                  sortBy: sort.sortBy,
              },
              records: populatedRecords.map((r) => r.toJSON(context.currentAdmin)),
          };
      },
  };
  
  module.exports = {
      Action,
  };

// index.js -> [Your Initializing script]


.....
const AdminJS = require('adminjs');
const { Action } = require('./globals');

// Add custom global action handler befor initializing adminJs
AdminJS.ACTIONS.list.handler = Action.list

// Set up admin
const adminJs = new AdminJS({....});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Filtering and search by ID does not work · Issue #737 - GitHub
Describe the bug Filtering and search by ID does not work. As far as I understand, @admin-bro/mongoose has wrong cast of type ObjectId....
Read more >
Search for data using filter function not working - Stack Overflow
I put below the code with a generic filter function. One more thing, if the string is empty, there is no reason to...
Read more >
Filter on Sharepoint List Not Working with ID
Solved: I'm connected to a sharepoint list that has only 470 records. It's a list of projects where users can enter and update...
Read more >
GraphQL Search and Filter – How to search and filter results ...
Let's try this: type AlbumsFilters = { genre: Genre ids: [ID!] } type AlbumsInput = { filter: AlbumsFilters } type Query { album(id:...
Read more >
How to search by Name from another view then filter by ID ...
This problem can be solve by using Liquid variables and the parameter parameter. In the Customer view, concatenate the ID, first name, and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found