GraphQLGuide / apollo-datasource-mongodb

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

Handle Mongoose reference fields #27

Closed NeoTheThird closed 4 years ago

NeoTheThird commented 4 years ago

Since this lib uses the default client to talk to mongodb, mongoose references are not understood.

If i use a model like this:

const SomeModel = mongoose.model(
  "Some",
  mongoose.Schema({
    data: { type: String },
    other: { type: "ObjectId", ref: "Other" }
  })
);

const OtherModel = mongoose.model(
  "Other",
  mongoose.Schema({
    whatever: { type: String }
  })
);

Would return something like this:

{
  _id: "ObjectId(1337)",
  data: "here be dragons",
  other: "ObjectId(1234)"
}

Instead of what you would expect:

{
  _id: "ObjectId(1337)",
  data: "here be dragons",
  other: {
    _id: "ObjectId(1234)"
  }
}

Obviously it's possible to work around this by re-mapping the object in js (which is ugly but works) or by using mongoose's methods rather than the default findOneById (which makes it impossible to use the built-in cache). Maybe it could be an option to use have findOneById actually use mongoose for find operations, if the constructor was passed a model instead of a collection? There would be more benefits, such as the possibility to cache Mongoose's virtuals.

treffiletti commented 4 years ago

@NeoTheThird how are you remapping this in JS? I'm hitting hte same issue...

lorensr commented 4 years ago

@NicholasAnthony have you tried updating to v0.2.7? Also, new section of README:

If you're passing a Mongoose model rather than a collection, Mongoose will be used for data fetching. All transformations definded on that model (virtuals, plugins, etc.) will be applied to your data before caching, just like you would expect it. If you're using reference fields, you might be interested in checking out mongoose-autopopulate.