Sequelize Group By Returns Not All Attributes - postgresql

I am trying to write a query to returns everything that a device has.
Currently my query is:
var getHardwareData = function() {
return Device.findAll({
where: {
ownerId: req.account.id
},
attributes: [
'"hardwareName"',
[Sequelize.fn('COUNT', '*'), 'count'],
],
group: '"hardwareName"',
}).then(function(devices) {
return devices;
});
};
I want to have hardwareName and the count of it. Currently it returns count: 1 and only it.

Related

Prisma splice Item from Array

I have been pushing updates to an array and was wondering if there is a built-in method to remove an entry from the array as well. Basically reversing the push command. I suspect that I have to query all documents and remove the item myself. But maybe there is some functionality I was unable to find inside the documentation.
Push:
const addTag = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
push: 'computing',
},
},
})
Remove Expectation:
const removeTag = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
splice: 'computing',
},
},
})
As of writing, there's no method to splice/remove items from a scalar list using Prisma. You would have to fetch the scalar list from your database, modify it manually in your application code and overwrite the record in your database with an update operation.
There is a feature request for this, please feel free to follow/comment with your use-case to help us track demand for this feature.
const { dogs } = await prisma.user.findOne({
where: {
id: userId
},
select: {
dogs: true
},
});
await prisma.user.update({
where: {
id: userId
},
data: {
dogs: {
set: dogs.filter((id) => id !== 'corgi'),
},
},
});

Why I'm I getting an error saving date using graphql > hasura > postgres

I'm using react, apollo, graphql, hasura, postgres as my stack to interact with the database. I think my issue is something small, so I'll just focus on the part that's not working rather than posting the whole code.
Thanks.
Error: GraphQL error: unexpected variables in variableValues: birthday
at new ApolloError (bundle.esm.js:63)
at Object.next (bundle.esm.js:1004)
at notifySubscription (Observable.js:135)
at onNotify (Observable.js:179)
at SubscriptionObserver.next (Observable.js:235)
at bundle.esm.js:866
at Set.forEach (<anonymous>)
at Object.next (bundle.esm.js:866)
at notifySubscription (Observable.js:135)
at onNotify (Observable.js:179)
at SubscriptionObserver.next (Observable.js:235)
at bundle.esm.js:76
variables{ id: 2324324, name: "Fred", birthday: "1991-01-11" }
If i remove birthday the query works.
Here is the function
const onUpdateUser = (options) => {
updateUser({
variables: Object.assign({ id: userId }, options),
optimisticResponse: {
__typename: "mutation_root",
update_users: {
__typename: "users_mutation_response",
affected_rows: 1,
returning: [
{
__typename: "users",
id: userId,
...options,
},
],
},
},
});
};
input {birthday: '1991-01-11'}
So without looking at your graphql query, I think you may be thinking of it a little bit off.
You can't dynamically add non-existent variables to a graphql query. The error is telling you that you are trying to add a variable that doesn't exist in your query
i.e. this with NOT work because you haven't defined birthday.
mutation updateUser(
$userId: Int!
$birthday (UNDEFINED)
) {
rest of query...
}
If you need to add a dynamic amount of variables, you could do something like this.
React Code
const onUpdateUser = (options) => {
updateUser({
variables: {
userId,
userVariables: options
},
optimisticResponse: {
__typename: "mutation_root",
update_users: {
__typename: "users_mutation_response",
affected_rows: 1,
returning: [
{
__typename: "users",
id: userId,
...options,
},
],
},
},
});
};
GraphQL mutation
mutation updateUser(
$userId: Int!
$userVariables: user_set_input!
) {
update_user(
where: { id: { _eq: $userId} }
_set: $userVariables
) {
affected_rows
}
}
https://hasura.io/docs/1.0/graphql/manual/mutations/update.html

Execute an aggregate query inside a mongo function

None of the examples show doing a simple sum inside a function, how do I do an aggregate query from a function?
Basically just trying to store a collection of known queries as a function on Mongo
you can define your queries as functions. Assume below schema of posts in a blog that you can save it as favourite. If you need to increase or decreasefavCount you can perform it as below,
const PostSchema = new Schema(
{
//other necessary fields as title, description of the post..etc
favoriteCount: {
type: Number,
default: 0,
},
},
{ timestamps: true },
);
PostSchema.statics = {
incFavoriteCount(postId) {
return this.findByIdAndUpdate(postId, { $inc: { favoriteCount: 1 } });
},
decFavoriteCount(postId) {
return this.findByIdAndUpdate(postId, { $inc: { favoriteCount: -1 } });
}
};
export default mongoose.model('Post', PostSchema);

Distinct Query with Cloudant Connector using Loopback in API Connect/StrongLoop

I am trying to get distinct values for a query using Loopback with a Cloudant Connector, but I haven't found anything about this in the documentation.
e.g. I need a query to turn this:
[
{
rating: "★★★★★"
},
{
rating: "★★★★★"
},
{
rating: "★★★★★"
},
{
rating: "★★★★★"
},
{
rating: "★★★☆☆"
},
{
rating: "★★★☆☆"
}
]
into this:
[
{
rating: "★★★★★"
},
{
rating: "★★★☆☆"
}
]
I'm using the REST API to query my Products model (above is a filtered view of just the rating field). If there is some sort of filter that I can use without modifying the server that I somehow just missed in the documentation, that would be the best choice.
Is there any way I can add a distinct field like:
/Products?filter[fields][rating]=true?distinct=true
or how can I go about solving this?
Also, I've seen another answer talking about adding a remote method to solve this (something like this for mySQL):
Locations.regions = function (cb) {
var ds = Locations.app.datasources.myDS;
var sql = "SELECT DISTINCT region FROM Locations ORDER BY region"; // here you write your sql query.
ds.connector.execute(sql, [], function (err, regions) {
if (err) {
cb(err, null);
} else {
cb(null, regions);
}
});
};
Locations.remoteMethod(
'regions', {
http: {
path: '/regions',
verb: 'get'
},
returns: {
root: true,
type: 'object'
}
}
);
If this would work, how would I implement it with the Cloudant NoSQL DB connector?
Thanks!
If your documents looked like this:
{
"name": "Star Wars",
"year": 1978,
"rating": "*****"
}
You can create a MapReduce view, which emits doc.rating as the key and uses the build-in _count reducer:
function(doc) {
emit(doc.rating,null);
}
When you query this view with group=true, distinct values of rating will be presented with counts of their occurrence in the data set.

Meteor: How to subscribe to different publications for different templates on the same page?

I have two templates that I'd like to render on the same page. One is a template that lists recent items; the other one lists items that are $text search results.
Data for each template is from a separate subscription. The problem is, minimongo doesn't support $text search, so I can't use $text to limit results from the client once the subscriptions are returned. That's a problem because both subscriptions are mixed together at the client side, so both my search results and recent items results look weird, because they each draw from both subscriptions.
I'm attempting to deal with it by using Iron Router to specify which template subscribes to which publication. However, my code doesn't work.
on the server, the file app.js, two separate publications:
if (Meteor.isServer) {
Meteor.publish("myitems", function () {
return Items.find();
});
Items._ensureIndex({
"itemName": "text",
//"tags" : "text"
});
Meteor.publish("search", function (searchValue) {
if (!this.userId) {
this.ready();
return;
}
return Items.find(
{
createdBy: this.userId,
$text: {$search: searchValue},
retired: {$ne: true}
},
{
fields: {
score: {$meta: "textScore"}
},
sort: {
score: {$meta: "textScore"}
}
}
);
});
}
client side code:
helper for the recent items template:
Template.myitems.helpers(
{
items: function () {
var d = new Date();
var currentUser = Meteor.userId();
return Items.find(
{
createdBy: currentUser,
createdAt: {
$gte: new Date(d.setDate(d.getDate() - 30))
}
},
{
sort: {
createdAt: -1
},
limit: 5
});
}
});
helper for the search results template:
Template.searchResults.helpers({
searchitems: function () {
if (Session.get("searchValue")) {
return Items.find({
}, {
sort: {"score": -1, "itemName": -1},
//limit: 10
});
} else {
//return Items.find({});
}
}
});
}
onCreated subscription for each template, separately:
Template.myitems.onCreated (function () {
Meteor.subscribe('myitems');
});
Template.searchResults.onCreated (function () {
Meteor.subscribe('search');
});
Router controller configuration: yes you'll see that it attempts to subscribe as well, but it fails anyway, so there's no duplicate subscription to "myitems"
itemsController = RouteController.extend({
//waitOn: function() {
// return [
// Meteor.subscribe('myitems')
// ];
//},
//data: function() {
// //return { items : Items.find({}), item_id : this.params._id }
// return {items: Items.find()};
//},
action: function() {
this.render('items');
this.render('searchitems', {to: 'region1'});
this.render('myitems', {
to: 'region3',
waitOn: function() {
return [
Meteor.subscribe('myitems')
];
},
data: function(){
return {items: Items.find()};
}
});
}
});
The above iron router code doesn't attempt to subscribe to the search publication. It attempts to subscribe to the recent items ('myitems') publication, but somehow the returned "items" is empty. The issue is not due to any wrong setting in the publication, because the commented out code works: if it were uncommented, then "items" do get returned and isn't empty, even if I don't use onCreated to subscribe to it.
My questions are:
what's wrong with the above code? I know that the subscription to "myitems" fail from the Iron Router. The subscription to "myitems" succeeds in the "onCreate", but the search results also draws from "myitems", instead of drawing from "searchResults" only.
assuming I can fix the above code, is Iron Router the way to go to solve my original problem: the search results subscription and the recent items subscription need to be separate, although the two templates are to be rendered on the same webpage?