lomse
lomse

Reputation: 4165

feathers-mongodb Service.find({query: {_id}}) returns null

I have the schemas below:

students.graphql.schema.js

export default [
  `
  type StudentsWithPagination {
    total: Int
    items: [Students]
  }

  type Students {
    _id: String!
    name: String
    address: Addresses
  }
`,
];

addresses.graphql.schema.js

export default [
      `
  type AddressesWithPagination {
    total: Int
    items: [Addresses]
  }

  type Addresses {
    _id: String!
    title: String
  }
`,
];

I have created two services by running feathers generate service students.service.js and addresses.services.js.

When I search addresses by title, I get result. However, when I search by _id, I get null. Something like:

const studentsResolvers = {
    Students: {
        address: student => {
            const query = {
                _id: student.address
            }
            return Addresses.find({ query }).then(result => {
                console.log(result)
            })
        }
    }
}

The code above produces null though student.address returns the right address._id. I still get null even I hardcode student.address with the right address._id

The code above will return null unless I search by address title. Something like:

const query = {
   title: 'my-location'
}

_id is of type String, not ObjectID.

What am I doing wrong?

Upvotes: 0

Views: 1510

Answers (1)

Daff
Daff

Reputation: 44215

As documented in the feathers-mongodb adapter, since MongoDB itself (unlike Mongoose) does not have a schema, all query parameters have to be converted to the type in the database in a hook manually. The example can be adapted accordingly for $in queries:

const ObjectID = require('mongodb').ObjectID;

app.service('users').hooks({
  before: {
    find(context) {
      const { query = {} } = context.params;

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

      if(query.age !== undefined) {
        query.age = parseInt(query.age, 10);
      }

      context.params.query = query;

      return Promise.resolve(context);
    }
  }
});

Upvotes: 1

Related Questions