boing
boing

Reputation: 539

How to query for ObjectIds in feathersjs that are normal fields?

I have a collection of product variants, i.e., different versions of the same product. There's a separate product collection. Variant documents have a product_id field, which holds the ObjectId of the corresponding product document in the product collection; its type is ObjectId. All searches on this field return 0 records. If I change the type to String, I can search successfully.

The service processing these searches uses feathersjs. I thought the correct way to structure my query for feathers would be this:

  const params = {
    'params': {
      'query': {
        'product_id': ObjectId(productId)
      }
    }
  };

When I do that, the params arrive at the server like this:

{ 
    query: { 
        product_id: { 
            id: '\\îĦ ;ÌúgÄ' 
        } 
    } 
}

That's what I see if I console.log the value at the client side, so I'm confident that the transport is working correctly.

Like I said, if I change the data type of a value to a String, I can get the search results I expect by doing:

  const params = {
    'params': {
      'query': {
        'product_id': productId
      }
    }
  };

I'm stumped here and don't know what else to try. I'm sure this is possible because I can query for _id fields with no problems. Any help would be appreciated.

Upvotes: 2

Views: 1250

Answers (1)

Daff
Daff

Reputation: 44215

Conversion to the internal type should happen on the server. This can be done in a hook similar to the one from this issue:

const { ObjectID } = require('mongodb');

module.exports = function() {
  return async context => {
    const { query = {} } = context.params;

    if(query. product_id) {
      query.product_id = new ObjectID(query._id);
    }

    return context;
  }
}

Upvotes: 3

Related Questions