Skip to content

Commit fac141a

Browse files
mattslightnodkz
authored andcommitted
docs: pushing elements to arrays in update method
* Update FAQs in README.md for pushing to arrays Addresses #35 * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md
1 parent f6a66f6 commit fac141a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,32 @@ schemaComposer.Mutation.addFields({
443443
}),
444444
});
445445
```
446+
### How can I push/pop or add/remove values to arrays?
447+
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.
448+
449+
For example (push):-
450+
451+
```javascript
452+
// Define new resolver 'pushToArray'
453+
UserTC.addResolver({
454+
name: 'pushToArray',
455+
type: UserTC,
456+
args: { userId: 'MongoID!', valueToPush: 'String' },
457+
resolve: async ({ source, args, context, info }) => {
458+
const user = await User.update({ _id: args.userId }, { $push: { arrayToPushTo: args.valueToPush } } })
459+
if (!user) return null // or gracefully return an error etc...
460+
return User.findOne({ _id: args.userId }) // return the record
461+
}
462+
})
463+
464+
// Then add 'pushToArray' as a graphql field e.g.
465+
schemaComposer.rootMutation().addFields({userPushToArray: UserTC.getResolver('pushToArray')})
466+
```
467+
468+
`User` is the corresponding Mongoose model. If you do not wish to allow duplicates in the array then replace `$push` with `$addToSet`. Read the graphql-compose docs on custom resolvers for more info: https://graphql-compose.github.io/docs/en/basics-resolvers.html
469+
470+
NB if you set `unique: true` on the array then using the `update` `$push` approach will not check for duplicates, this is due to a MongoDB bug: https://jira.mongodb.org/browse/SERVER-1068. For more usage examples with `$push` and arrays see the MongoDB docs here https://docs.mongodb.com/manual/reference/operator/update/push/. Also note that `$push` will preserve order in the array (append to end of array) whereas `$addToSet` will not.
471+
446472

447473
## Customization options
448474

0 commit comments

Comments
 (0)