简体   繁体   中英

How can I filter records by their ObjectID (_id) in Ag-grid

I'm using MongoDB to store my records and am using Ag-grid react to display them. The grid has several columns including the record's ObjectID (_id), name, type, etc. Using the filter agColumnTextFilter works for the name and type fields with the columnDef of:

{
  headerName: 'Column Name',
  field: 'name',
  filter: 'agTextColumnFilter',
},

which then leads to this query setup (using the contains filter option):

case "contains":
  qp[fieldName] = new RegExp(['.*', user input string, '.*'].join(''), 'ig');

this logs the correct query:

"query db { name: /.*query string.*/gi }"

and the proper rows are displayed. Since the displayed _id is a string as well I tried something similar:

{
  headerName: 'ID',
  field: '_id',
  valueGetter: (params) => {
    let id = params.data._id;
    return id.slice(id.length-5); //only display last part of ID instead of entire thing
  },
  filter: 'agTextColumnFilter',
},

Using the same contains logic as above the following query is logged to the console:

query db { _id: /.*_id segment.*/gi }

However, no rows are returned in this case (even though there should be rows returned). Do I need to use different logic or is there a problem with this current logic? Any advice is appreciated.

Edit: Turns out even though the ID displays as a String a cast of the string to an ObjectID is needed:

qp[fieldName] = new ObjectID(_id string)

Problem with this is searching for part of a specific ID won't work because it's not a valid ID. Searching for a full ID works but isn't ideal either. If anyone has any ideas on how I can filter just part of the ID I'd appreciate it.

You can probably set a valueFormatter on the column that displays the partial ObjectId. The filtering will be done using the full ObjectId.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM