Solving relationships in Mongoose and GraphQL

↘锁芯ラ 提交于 2021-01-29 09:55:47

问题


So, I have this app that I'm starting and I'm going with MERNG stack using Apollo.

I was doing research by reading blog posts and watching videos in order to have a better understanding of how GraphQL works (never actually worked with it). At some point, I started to see examples of relationships between db models such as "posts from a user".

For example:

    import { model, Schema } from 'mongoose'; 

    const postSchema = new Schema(
    { 
      title: String,
      createdBy {
        type: Schema.Types.ObjectId,
        ref: 'User',
      }
    };

    export default model('Post', postSchema);

    import { model, Schema } from 'mongoose'; 

    const userSchema = new Schema(
    { 
      email: String,
      password: String,
      posts [{
        type: Schema.Types.ObjectId,
        ref: 'Post',
      }]
    }

    export default model('User', userSchema);

I was wondering which will be the best approach to "populate" related fields when doing queries to retrieve the user data in the posts.

As I saw there's two options:

1 - Using populate which comes with Mongoose. This has the disadvantage that it will always populate the field even if I don't ask for it in the GraphQL query. 2 - Using a function that will use a findById to retrieve the related object and then manually assign it. This does not have the issue of the populate as it will only get it when the field is needed, instead it increases the number of times I have to query the database.

I understand both pros and cons but I'm not sure which would be the best solution for this. Is there any other option that I'm missing?


回答1:


Your 2nd option was not good for database because if you get millions of record from a database another millions of hit automatically worked when you call the particular field.

Your 1st option also not good for your expectation. because you want particular field or not it's automatically invoked.

So I hope it's better solution for you. Your can get what the fields asking from client side (you can use custom decorator for get those fields). Then you should use aggregation for get a what you want. Then you decide $lookup is invoke or not with the help of your fields(just use if condition).

note: Resolve property should not hit your database because the reason was you already know.

I hope its may help you



来源:https://stackoverflow.com/questions/59483032/solving-relationships-in-mongoose-and-graphql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!