GraphQLGuide / apollo-datasource-mongodb

Apollo data source for MongoDB
MIT License
285 stars 64 forks source link

Support class-based mongoose models #51

Closed SleepWalker closed 3 years ago

SleepWalker commented 3 years ago

Hello, I'm trying to use this package together with mongoose and getting MongoDataSource constructor must be given a collection or Mongoose model.

This is the way I'm creating datasource instance:

new ApolloServer({
    // ...
    dataSources: (): => ({
      users: new Users(User),
    }),
});

This is how I create models:

const schema = mongoose.Schema(...);

class User extends mongoose.Model {}

export default mongoose.model(User, schema);

The error is because of x.name === 'model' from here:

https://github.com/GraphQLGuide/apollo-datasource-mongodb/blob/09e39275d4e47ae37418cb12f5cab583a2fad137/src/helpers.js#L3

If Mongoose model is compiled from class, it will inherit its constructor name. The name will be equal to model only in case, when you pass a string as first arg to mongoose.model() because in that case the constructor will be function model() {}:

https://github.com/Automattic/mongoose/blob/1bb97ba8caaf0cbcd4e3bee1238eae92722cc59b/lib/model.js#L4698-L4705