How to get an array or list as result from a graphql query? - mongodb

Hello I am new to graphql and I was wondering if it is possible to create a root query in my schema that will return an array or list as a result.
To be more precise I have created the following type in my schema:
const ResourceType = new GraphQLObjectType({
name:'Resource',
fields:()=>({
id: {type: GraphQLID},
url: {type: GraphQLString},
title: {type: GraphQLString},
author: {type: GraphQLString},
license:{type: GraphQLString},
LicenseScore: {type: GraphQLFloat},
})
});
And I want to query all the resources in my database so that I get their license type and then assign a score according to the license. Is it possible to have a query that gets the license for each resource and returns an array like this: [[id:1209,score:3.5],[1203,4.5]....]?
I have created a mutation that updates the score to the database, here it is:
updateAllLicenses: {
type: new GraphQLList(ResourceType),
async resolve(parent,args){
var licns;
var scr;
await Resource.find({}).then(async function(results){
var num = results.length;
var scr=0;
for (var i=0; i<num; i++){
if (! (results[i].license in licenseScores)){
scr = 0;
}
else{
scr = licenseScores[results[i].license];
}
await Resource.findByIdAndUpdate(results[i].id{LicenseScore:scr});
}
});
return await Resource.find({});
}
}
However I was wondering if there is a way to get these scores directly from the query instead of saving them in the database. I tried changing the type to new GraphQLList(GraphQLFloat) and returning an array with the scr values but I get an error in the graphql api saying I have the wrong output type in my mutation.

From your schema, it seems to me that you are able to fetch results, as an array of objects, with an output like this:
[
{
id: 1,
license: "value1"
},
{
id: 2,
license: "value2"
}
]
If this is all you need, then the approximate query should work:
query Resource {
id
url
license
licenseScore
}
Once you have your array of objects, you can convert it to an array of arrays, although I would not advise that.
Since you are just getting started in GraphQL, I recommened these resources:
HowToGraphql: clean videos/posts on GraphQL
Apollo Graphql's documentation and blogs. Here is one of the posts on queries
Also, if you want to test your queries and get accustomed to them, use GraphQL Playground

Related

Mongoose $in [ObjectIds] returns 0 records

In our Mongoose model, we have a product referring to an article.
this is a piece of the schema:
const product = new Schema({
article_id: Schema.Types.ObjectId,
title: String,
description: String,
...
In the API we are looking for products that are referring to a list of specific articles, and I wanted to use the $in operator:
const articles = ["5dcd2a95d7e2999332441825",
"5dcd2a95d7e2999332441827",
"5dcd2a96d7e2999332441829"]
filter.article_id = {
$in: articles.map(
article => new mongoose.Types.ObjectId(article)
),
};
return Product.find({ ...filter })
This returns 0 records, whereas I know for sure it should have returned at least 3. Looking at the console log, all that has happened is that the double quotes have been removed from the array during the ObjectId conversion.
Then I tried a different approach by returning {$oid: "id goes here"} for each mapped array item:
const articles = ["5dcd2a95d7e2999332441825",
"5dcd2a95d7e2999332441827",
"5dcd2a96d7e2999332441829"]
filter.article_id = {
$in: articles.map(
article => ({$oid: article})
),
};
return Product.find({ ...filter })
This gives a different array:
console.log(filter);
// {article_id: {$in: [{$oid: "5dcd2a95d7e2999332441825"}, {$oid: "5dcd2a95d7e2999332441827"}, {$oid: "5dcd2a96d7e2999332441829"}]}}
But in this case I get following error:
CastError: Cast to ObjectId failed for value "\"{$oid: \"5dcd2a95d7e2999332441825\"}\"".
Though - if I take that particular console logged filter and pass it in Studio 3T as a filter, I do indeed get the desired results.
Any idea what I doing wrong in this case?
Frick me! I am just a big idiot.. Apparently there was a .skip(10) added after the find() method -.-'.... Now I understand why 0 records where returned... Been spending hours on this..
For future references, Mongoose casts strings to ObjectIds automatically if defined in Schema. Therefor following is working exactly as it should given you don't skip the first 10 records:
const articles = ["5dcd2a95d7e2999332441825",
"5dcd2a95d7e2999332441827",
"5dcd2a96d7e2999332441829"]
filter.article_id = {
$in: articles
};
return Product.find({ ...filter }) // Note that I DON'T put .skip() here..

How to find string in array using Mongoose?

I have a schema through mongoose:
const mongoose = require('mongoose');
const recipeSchema = mongoose.Schema({
title: String,
chef: String,
updated: {type: Date, default: Date.now},
region: String,
ingredients: [String],
instructions: [String]
}, { collection: 'recipes' })
module.exports = mongoose.model('Recipes', recipeSchema);
I find the mongoose docs really difficult to understand. I am trying to search for a match of all substring within the 'ingredients' array. I read somewhere that it could be done like so:
.find({ingredients: 'ing1'}) // not working
.find({'ing1': {$in: ingredients}}) // not working
I find it pretty difficult to find in depth tutorials on mongoose as well. Im thinking about not using it at all anymore and just sticking to mongodb shell.
You can use a regex search to match substrings:
.find({ingredients: /ing1/})
The reason that you use mongoose is for testability.
Instead of having to work with a MongoDb instance, which, in Windows can be a pain with the .lock file and the service, mongoose creates the schema that you can test your code with.
The mongoose way is ideal for TDD/TFD.
Below is the model and the mocha test:
recipemodel.js
var mongoose = require('mongoose'),Schema=mongoose.Schema;
var RecipeSchema = new mongoose.Schema({});
RecipeSchema.statics.create = function (params, callback) {
'\\ params is any schema that you pass from the test below
var recipe = new RecipeSchema(params);
recipe.save(function(err, result) {
callback(err, result);
});
return recipe;
};
var recipemodel=mongoose.model('Model', RecipeSchema);
module.exports = recipemodel;
You don't need to describe the schema, mongoose will create it for you when you pass the values of the collection from a mocha test, for example!
The mocha test is below:
var mongooseMock = require('mongoose-mock'),
proxyquire = require('proxyquire'),
chai = require('chai'),
expect = chai.expect,
sinon = require('sinon'),
sinonChai = require("sinon-chai");
chai.use(sinonChai);
describe('Mocksaving a recipe ingredient', function () {
var Recipe;
beforeEach(function () {
Recipe = proxyquire('./recipemodel', {'mongoose': mongooseMock});
});
it('checks if ingredient '+'ing1' + ' saved to mongoose schema', function
(done) {
var callback = sinon.spy();
var recipe = Recipe.create({ title: "faasos", chef:
'faasos',region:'Chennai',ingredients:'ing1',instructions:'abc' },
callback);
expect(recipe.save).calledOnce;
expect(recipe.ingredients).equals('ing341');
done();
});
});
The call to a sinon spy is simply to ensure that the call to the data in the schema got saved (mock saved!) and that the 'save' method did get called at least once. This logic flow is in sync with your actual logic, as you would use in code, when the save on a mongodb collection would be made.
Simply change the value to 'ing1' to make the test pass when you run the test.
For an array type, pass the values as below:
var recipe = Recipe.create({ title: "faasos", chef:
'faasos',region:'Chennai',ingredients:'ing341,ing1',instructions:'abc' }, callback);
expect(recipe.save).calledOnce;
expect(recipe.ingredients).to.include('ing1');
Try this:
.ingredients.find((i) => i === "ing1")
for all elements in the ingredients array, it looks if the content, here a string element, is strictly equal to "ing1"

Store contents with rest proxy giving incorrect count

ExtJS 5.1.x, with several stores using rest proxy.
Here is an example:
Ext.define('cardioCatalogQT.store.TestResults', {
extend: 'Ext.data.Store',
alias: 'store.TestResults',
config:{
fields: [
{name: 'attribute', type: 'string'},
{name: 'sid', type: 'string'},
{name: 'value_s', type: 'string'},
{name: 'value_d', type: 'string'}
],
model: 'cardioCatalogQT.model.TestResult',
storeId: 'TestResults',
autoLoad: true,
pageSize: undefined,
proxy: {
url: 'http://127.0.0.1:5000/remote_results_get',
type: 'rest',
reader: {
type: 'json',
rootProperty: 'results'
}
}
}
});
This store gets populated when certain things happen in the API. After the store is populated, I need to do some basic things, like count the number of distinct instances of an attribute, say sid, which I do as follows:
test_store = Ext.getStore('TestResults');
n = test_store.collect('sid').length);
The problem is that I have to refresh the browser to get the correct value of 'n,' otherwise, the count is not right. I am doing a test_store.load() and indeed, the request is being sent to the server after the .load() is issued.
I am directly querying the backend database to see what data are there in the table and to get a count to compare to the value given by test_store.collect('sid').length);. The strange thing is that I am also printing out the store object in the debugger, and the expected records (when compared to the content in the database table) are displayed under data.items array, but the value given by test_store.collect('sid').length is not right.
This is all done sequentially in a success callback. I am wondering if there is some sort of asynchronous behavior giving me the inconsistent results between what is is the store and the count on the content of the store?
I tested this with another store that uses the rest proxy and it has the same behavior. On the other hand, using the localStorage proxy gives the correct count consistent with the store records/model instances.
Here is the relevant code in question, an Ajax request fires off and does its thing correctly, and hit this success callback. There really isn't very much interesting going on... the problem section is after the console.log('TEST STORE HERE'); where I get the store, print the contents of the store, load/sync then print the store (which works just fine) and then finally print the length of uniquely grouped items by the sid attribute (which is what is not working):
success: function(response) {
json = Ext.decode(response.responseText);
if(json !== null && typeof (json) !== 'undefined'){
for (i = 0, max = json.items.length; i < max; i += 1) {
if (print_all) {
records.push({
sid: json.items[i].sid,
attribute: json.items[i].attribute,
string: json.items[i].value_s,
number: json.items[i].value_d
});
}
else {
records.push({
sid: json.items[i].sid
})
}
}
//update store with data
store.add(records);
store.sync();
// only add to store if adding to search grid
if (!print_all) {
source.add({
key: payload.key,
type: payload.type,
description: payload.description,
criteria: payload.criteria,
atom: payload.atom,
n: store.collect('sid').length // get length of array for unique sids
});
source.sync();
}
console.log('TEST STORE HERE');
test_store = Ext.getStore('TestResults');
test_store.load();
test_store.sync();
console.log(test_store);
console.log(test_store.collect('sid').length)
}
// update grid store content
Ext.StoreMgr.get('Payload').load();
Ext.ComponentQuery.query('#searchGrid')[0].getStore().load();
}
For completeness, here is the data.items array output items:Array[2886]
which is equivalent count of unique items grouped by the attribute sid and finally the output of console.log(test_store.collect('sid').length), which gives the value from the PREVIOUS run of this: 3114...

cryptic mongodb error LEFT_SUBFIELD only supports Object: stats not: 6

I'm having trouble figuring out what this error means
LEFT_SUBFIELD only supports Object: stats not: 6
It seems to be happening when I am inserting into my profiles collection. I am using mongoose.js. We are inserting counts of posts in each category in the stats property, e.g.
stats: {category:count, category2: count2}.
Here is my schema
var ProfileSchema = new Schema({
uname: {
type: String,
required: true,
index: true,
unique: true
},
fname: String,
lname: String,
stats: {
type:{},
"default":{},
required:true
},
created: {
type:Date,
required:true,
"default":Date.now
}
});
I think it might be happening when I am updating the stats object $inc counts so that stats can come out to something like this update
db.status.update({_id:xyz}, {$inc: { stats.foo : 1, stats.bar:1}})
Here's my mongoose code
var tags = ["comedy", "action", "drama"];
//also adding the postId to the posts collection of profile
var updateCommand = {$push: {posts: post._id}};
var stats = {};
for (var i = tags.length - 1; i >= 0; i--){
stats["stats." + tags[i].toString()] = 1;
};
updateCommand.$inc = stats;
Profile.update(
{uname: uname},
updateCommand,
{safe:true, upsert:true},
callback
);
It also happens if you're trying to update a subdocument of a non-object.
> db.test.insert({_id: 10240292, object: 'some string'})
> db.test.update({_id: 10240292}, {$set: {'object.subkey': 'some string'}})
LEFT_SUBFIELD only supports Object: object not: 2
Maybe it's not your case, but it can help somebody who googles for this error.
You may be running into this:
https://jira.mongodb.org/browse/SERVER-2651
or
https://jira.mongodb.org/browse/SERVER-5227
Both of which are fixed in the 2.1 dev branch already but not (yet) backported to 2.0
There is a decent discussion here about a similar issue:
https://groups.google.com/forum/?fromgroups#!topic/mongodb-user/VhjhcyEdbNQ
Basically it boils down to the fact that you are likely passing an empty key as part of the update which needs to be avoided.
db.collection('fs.files').update({_id: Object_id}, {$set: {'metadata': {"foo" : "bar"}}}

Is it possible to extract only embedded documents from a Model in Mongoose?

I'd like to run a query on a Model, but only return embedded documents where the query matches. Consider the following...
var EventSchema = new mongoose.Schema({
typ : { type: String },
meta : { type: String }
});
var DaySchema = new mongoose.Schema({
uid: mongoose.Schema.ObjectId,
events: [EventSchema],
dateR: { type: Date, 'default': Date.now }
});
function getem() {
DayModel.find({events.typ : 'magic'}, function(err, days) {
// magic. ideally this would return a list of events rather then days
});
}
That find operation will return a list of DayModel documents. But what I'd really like is a list of EventSchemas alone. Is this possible?
It's not possible to fetch the Event objects directly, but you can restrict which fields your query returns like this:
DayModel.find({events.typ : 'magic'}, ['events'], function(err, days) {
...
});
You will still need to loop through the results to extract the actual embedded fields from the documents returned by the query, however.