I'm confused about what should be the relation between GraphQL's cursors and MongoDB's cursors.
I'm currently working on a mutation that creates an object (mongo document) and add it to an existing connection (mongo collection). When adding the object, the mutation returns the added edge. Which should look like:
{
node,
cursor
}
While node is the actual added document, I'm confused on what should be returned as the cursor.
This is my Mutation:
const CreatePollMutation = mutationWithClientMutationId({
name: 'CreatePoll',
inputFields: {
title: {
type: new GraphQLNonNull(GraphQLString),
},
multi: {
type: GraphQLBoolean,
},
options: {
type: new GraphQLNonNull(new GraphQLList(GraphQLString)),
},
author: {
type: new GraphQLNonNull(GraphQLID),
},
},
outputFields: {
pollEdge: {
type: pollEdgeType,
resolve: (poll => (
{
// cursorForObjectInConnection was used when I've tested using mock JSON data,
// this doesn't work now since db.getPolls() is async
cursor: cursorForObjectInConnection(db.getPolls(), poll),
node: poll,
}
)),
},
},
mutateAndGetPayload: ({ title, multi, options, author }) => {
const { id: authorId } = fromGlobalId(author);
return db.createPoll(title, options, authorId, multi); //promise
},
});
Thanks!
Probably a bit late for you, but maybe it will help someone else stumbling across this problem.
Just return a promise from your resolve method. Then you can create your cursor using your actual polls array. Like so:
resolve: (poll =>
return db.getPolls().then(polls => {
return { cursor: cursorForObjectInConnection(polls, poll), node: poll }
})
)
But careful, your poll and the objects in polls have different origins now and are not strictly equal. As cursorForObjectInConnection uses javascript's indexOf your cursor would probably end up being null. To prevent this you should find the object index yourself and use offsetToCursor to construct your cursor as discussed here.
Related
I can't figure this out.
I have an object in an array within another object which I need to update with mongoDB updateOne.
I make the call, it says it found it OK and has updated it ({ n: 1, nModified: 1, ok: 1 }). But then on checking no update is made in the database...
What am I doing wrong here?
Model
const pathwayDetailsSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
associatedPathwayID: {
type: mongoose.Schema.Types.ObjectId,
required: true
},
pages: [
{
_id: { type: String },
x: {
type: Number,
required: true
},
y: {
type: Number,
required: true
},
widgets: [
{
more nested objects..
}
]
}
]
}
Router call
router.post('/pageupdate/',auth, async(req,res)=>{
const pageID = req.body.pageID; //Page ID string
const pathwayID = req.body.pathwayID; // pathwayID string
const update = req.body.update; //{x: new X value, y: new Y value}
try{
console.log("receieved: ",pageID, pathwayID, update);
let updatedDoc = await PathwayDetails.updateOne(
{ associatedPathwayID: pathwayID, "pages._id": pageID },
{ $set: update}
);
console.log("successful? ",updatedDoc)
res.status(201).send(updatedDoc)
}
catch(e){
etc...
}
});
Changing x and y passes through fine and it says it updates. But on checking the database no change is made...
I think you have missed async keyword before await.
A function should be an async inorder to use the await keyword.
So, you wrap the code inside a async function.
Since you are not using the async function, await has lost it's functionality, so it's basically updating the old value again and again. It's not awaiting fo the new value. So you are not seeing any change in the value in the database even though the code is executed successfully.
Try the below code:
const update_document = async (req, res) => {
let updatedDoc = await PathwayDetails.updateOne(
{ associatedPathwayID: pathwayID, "pages._id": pageID },
{ $set: update}
);
res.status(201).send(updatedDoc)
};
After this call the update_document function with the router.
I think this will work.
Figured it out.
The update I was passing wasn't pointing to a nested object correctly.
Rather than update being {x: new X value, y: new Y value}
needed to pass a nested update it must be {"pages.$.x": new X value, "pages.$.y": new Y value}
It is annoying that mongo returns a response saying it has updated the database when it can't find the field to update!
Every tutorial I have found thus far has achieved pagination in GraphQL via Apollo, Relay, or some other magic framework. I was hoping to find answers in similar asked questions here but they don't exist. I understand how to setup the queries but I'm unclear as to how I would implement the resolvers.
Could someone point me in the right direction? I am using mongoose/MongoDB and ES5, if that helps.
EDIT: It's worth noting that the official site for learning GraphQL doesn't have an entry on pagination if you choose to use graphql.js.
EDIT 2: I love that there are some people who vote to close questions before doing their research whereas others use their knowledge to help others. You can't stop progress, no matter how hard you try. (:
Pagination in vanilla GraphQL
// Pagination argument type to represent offset and limit arguments
const PaginationArgType = new GraphQLInputObjectType({
name: 'PaginationArg',
fields: {
offset: {
type: GraphQLInt,
description: "Skip n rows."
},
first: {
type: GraphQLInt,
description: "First n rows after the offset."
},
}
})
// Function to generate paginated list type for a GraphQLObjectType (for representing paginated response)
// Accepts a GraphQLObjectType as an argument and gives a paginated list type to represent paginated response.
const PaginatedListType = (ItemType) => new GraphQLObjectType({
name: 'Paginated' + ItemType, // So that a new type name is generated for each item type, when we want paginated types for different types (eg. for Person, Book, etc.). Otherwise, GraphQL would complain saying that duplicate type is created when there are multiple paginated types.
fields: {
count: { type: GraphQLInt },
items: { type: new GraphQLList(ItemType) }
}
})
// Type for representing a single item. eg. Person
const PersonType = new GraphQLObjectType({
name: 'Person',
fields: {
id: { type: new GraphQLNonNull(GraphQLID) },
name: { type: GraphQLString },
}
})
// Query type which accepts pagination arguments with resolve function
const PersonQueryTypes = {
people: {
type: PaginatedListType(PersonType),
args: {
pagination: {
type: PaginationArgType,
defaultValue: { offset: 0, first: 10 }
},
},
resolve: (_, args) => {
const { offset, first } = args.pagination
// Call MongoDB/Mongoose functions to fetch data and count from database here.
return {
items: People.find().skip(offset).limit(first).exec()
count: People.count()
}
},
}
}
// Root query type
const QueryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
...PersonQueryTypes,
},
});
// GraphQL Schema
const Schema = new GraphQLSchema({
query: QueryType
});
and when querying:
{
people(pagination: {offset: 0, first: 10}) {
items {
id
name
}
count
}
}
Have created a launchpad here.
There's a number of ways you could implement pagination, but here's two simple example resolvers that use Mongoose to get you started:
Simple pagination using limit and skip:
(obj, { pageSize = 10, page = 0 }) => {
return Foo.find()
.skip(page*pageSize)
.limit(pageSize)
.exec()
}
Using _id as a cursor:
(obj, { pageSize = 10, cursor }) => {
const params = cursor ? {'_id': {'$gt': cursor}} : undefined
return Foo.find(params).limit(pageSize).exec()
}
Creating models in Mongoose is quite pointless since such models are already created with GraphQL and existing constructs (ie TypeScript interface).
How can we get GraphQL to use Mongoose's operations on models supplied from GraphQL without having to recreate models in Mongoose?
Also, it almost seems as if there should be a wrapper for GraphQL that just communicates with the database, avoiding having to write MyModel.findById etc
How does one do that?
Every example on the Internet that talks about GraphQL and Mongodb uses Mongoose.
You should look at GraphQL-to-MongoDB, or how I learned to stop worrying and love generated query APIs. It talks about a middleware package that leverages GraphQL's types to generate your GraphQL API and parses requests sent from clients into MongoDB queries. It more or less skips over Mongoose.
Disclaimer: this is my blog post.
The package generates GraphQL input types for your schema field args, and wraps around the resolve function to parse them into MongoDB queries.
Given a simple GraphQLType:
const PersonType = new GraphQLObjectType({
name: 'PersonType',
fields: () => ({
age: { type: GraphQLInt },
name: {
type: new GraphQLNonNull(new GraphQLObjectType({
name: 'NameType',
fields: () => ({
firstName: { type: GraphQLString },
lastName: { type: GraphQLString }
})
}))
}
})
});
For the most common use case, you'll build a field in the GraphQL schema with a getMongoDbQueryResolver and getGraphQLQueryArgs. The filter, projection, and options provided by the wrapper can be passed directly to the find function.
person: {
type: new GraphQLList(PersonType),
args: getGraphQLQueryArgs(PersonType),
resolve: getMongoDbQueryResolver(PersonType,
async (filter, projection, options, source, args, context) =>
await context.db.collection('person').find(filter, projection, options).toArray()
)
}
An example of a query you could send to such a field:
{
person (
filter: {
age: { GT: 18 },
name: {
firstName: { EQ: "John" }
}
},
sort: { age: DESC },
pagination: { limit: 50 }
) {
name {
lastName
}
age
}
}
There's also a wrapper and argument types generator for mutation fields.
I'm trying to update a sub document on an existing collection. I'm getting a MongoDB error message.
"MongoError: The positional operator did not find the match needed from the query. Unexpanded update: articleWords.$ [409]"
From my Articles Simple Schema
"articleWords.$": {
type: Object
},
"articleWords.$.wordId": {
type: String,
label: 'Word ID'
},
"articleWords.$.word": {
type: String,
label: 'Word'
},
Update Function
function updateArticle(_id,wordArr) {
_.each(wordArr,function(elem) {
var ret = Articles.update(
{'_id': _id},
{ $set: { 'articleWords.$': { 'wordId': elem.wordId, 'word': elem.word } }
});
});
return true;
}
As you can see I am passing an array of objects. Is there a better way to do this than _.each ?
CLARIFICATION
Thank you to #corvid for the answer. I think I didn't make my question clear enough. There does exist an article record, but there is no data added to the articleWords attribute. Essentially we are updating a record but insert into the articleWords array.
A second attempt, is also not working
_.each(wordArr,function(elem) {
var ret = Articles.update(
{'_id': _id},
{ $set: { 'articleWords.$.wordId': elem.wordId, 'articleWords.$.word': elem.word } }
);
});
Yes, you need your selector to match something within the subdocument. For example,
Articles.update({
'_id': <someid>,
'words.wordId': <somewordid>
}, {
$set: {
'words.$.word': elem.word,
'words.$.wordId': elem.wordId
}
});
If the array doesn't exist yet then you're going about this in the hardest way possible. You can just set the entire array at one go:
var ret = Articles.update(
{'_id': _id},
{ $set: { articleWords: wordArr }}
);
I can see that wordArr already has the id and string. This will work as long as it doesn't have more content. If it does then you can just make a second version with the parts you want to keep.
I have a Collection that has documents with an array of nested objects.
Here is fixture code to populate the database:
if (Parents.find().count() == 0) {
var parentId = Parents.insert({
name: "Parent One"
});
Children.insert({
parent: parentId,
fields: [
{
_id: new Meteor.Collection.ObjectID(),
position: 3,
name: "three"
},
{
_id: new Meteor.Collection.ObjectID(),
position: 1,
name: "one"
},
{
_id: new Meteor.Collection.ObjectID(),
position: 2,
name: "two"
},
]
});
}
You might be asking yourself, why do I even need an ObjectID when I can just update based off of the names. This is a simplified example to a much more complex schema that I'm currently working on and the the nested object are going to be created dynamically, the ObjectID's are definitely going to be necessary to make this work.
Basically, I need a way to save those nested objects with a unique ID and be able to update the fields by their _id.
Here is my Method, and the call I'm making from the browser console:
Meteor.methods({
upChild: function( options ) {
console.log(new Meteor.Collection.ObjectID());
Children.update({_id: options._id, "fields._id": options.fieldId }, {$set: {"fields.$.position": options.position}}, function(error){
if(error) {
console.log(error);
} else {
console.log("success");
}
});
}
});
My call from the console:
Meteor.call('upChild', {
_id: "5NuiSNQdNcZwau92M",
fieldId: "9b93aa1ef3868d762b84d2f2",
position: 1
});
And here is a screenshot of the html where I'm rendering all of the data for the Parents and Children collections:
Just an observation, as I was looking how generate unique IDs client side for a similar reason. I found calling new Meteor.Collection.ObjectID() was returning a object in the form 'ObjectID("abc...")'. By assigning Meteor.Collection.ObjectID()._str to _id, I got string as 'abc...' instead, which is what I wanted.
I hope this helps, and I'd be curious to know if anyone has a better way of handling this?
Jason
Avoid using the _str because it can change in the future. Use this:
new Meteor.Collection.ObjectID().toHexString() or
new Meteor.Collection.ObjectID().valueOf()
You can also use the official random package:
Random.id()