You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
### How can I restrict access to certain fields or documents?
1051
+
1052
+
This library allows modifying the query before it is executed using the `beforeQuery` hook. This lets us prevent certain fields or documents from being read. Here's an example of restricting access to specific fields:
// Don't change the projection and still allow all fields to be read
1062
+
} elseif (role==='moderator') {
1063
+
// Only allow the name, age, and gender fields to be read
1064
+
query.projection({ name: 1, age: 1, gender: 1 });
1065
+
} elseif (role==='public') {
1066
+
// Only allow the name field to be read
1067
+
query.projection({ name: 1 });
1068
+
}
1069
+
};
1070
+
1071
+
returnnext(rp);
1072
+
}),
1073
+
});
1074
+
```
1075
+
1076
+
Note that fields that are sometimes restricted should not be marked as required in the mongoose schema. Otherwise, when you query them you will get a "Cannot return null for non-nullable field" error because the database query didn't return a value for the field.
1077
+
1078
+
You can also use `beforeQuery` to hide certain documents from the query. Here's an example:
Both of these examples require putting extra data in the resolver context. Here's how to attach context data in Apollo Server:
1096
+
1097
+
```ts
1098
+
const server =newApolloServer({
1099
+
schema: schemaComposer.buildSchema(),
1100
+
context() {
1101
+
// This role should actually come from a JWT or something
1102
+
return { role: 'admin' };
1103
+
},
1104
+
});
1105
+
```
1106
+
1107
+
Other GraphQL servers are likely similar.
1108
+
1049
1109
### How can I push/pop or add/remove values to arrays?
1050
1110
1051
1111
The default resolvers, by design, will replace (overwrite) any supplied array object when using e.g. `updateById`. If you want to push or pop a value in an array you can use a custom resolver with a native MongoDB call.
0 commit comments