How should I filter data in Strapi by $and operator - next.js

I want to filter my table data by createdAt,status_invitor and status_invited. I write query Like this
const query = qs.stringify({
filters: {
$and: {
createdAt: { $gte: firstDayOfTheMonth },
createdAt: { $lt: lastDayOfTheMonth },
},
$and: {
status_invitor: statusFilter
},
status_invited: statusFilter,
},
});
but is not working correctly

The filters are combined by default so unless I have misunderstood what you are trying to achieve, you don't need to use the $and operator.
const query = qs.stringify({
filters: {
createdAt: { $gte: firstDayOfTheMonth },
createdAt: { $lt: lastDayOfTheMonth },
status_invitor: statusFilter,
status_invited: statusFilter,
},
});
If you do want to mix AND and OR filters then you need to specify an array. You can see examples of that here: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest/filtering-locale-publication.html#complex-filtering

I'm working on a project where I wanted to query more than one field with a search term. This is the code I used to get it working. I think all you need to do is change the $or for the $and and it should work.
const query = qs.stringify( {
filters: {
$or: [
{ name: { $contains: term }},
{ venue: { $contains: term } },
{ performers: { $contains: term } },
{ description: { $contains: term } },
],
},
},
)

Related

Wpgraphql queries under fetching queries from wordpress

I have this issue were I'm trying to request images I've uploaded on my WordPress instance with graphql from Gatsby but I only get the most recent item I uploaded on wordpress.
When i query using the Graphiql IDE on WordPress I the desired results. See this image ➡️
Image of the query and response in get from Graphiql IDE on wordpress
Below is the query and response in get from Graphiql IDE on wordpress
// Graphiql IDE query
{
mediaItems {
edges {
node {
databaseId
}
}
}
}
// The response
{
"data": {
"mediaItems": {
"edges": [
{
"node": {
"databaseId": 30
}
},
{
"node": {
"databaseId": 28
}
},
{
"node": {
"databaseId": 26
}
},
{
"node": {
"databaseId": 20
}
}
]
}
},
"extensions": {
"debug": []
}
}
but when I query from the http://localhost:8000/___graphql endpoint on my local development as I said earlier I only get the most recent upload.
Image of local development query and response
the code is below
// The query to http://localhost:8000/___graphql endpoint
{
wpMediaItem {
altText
localFile {
childImageSharp {
gatsbyImageData(placeholder: TRACED_SVG, width: 100)
id
}
}
}
}
// The response
{
"data": {
"wpMediaItem": {
"altText": "background lines",
"localFile": {
"childImageSharp": null
}
}
},
"extensions": {}
}
The ednpoints I can query
the enpoints img 1
the enpoints img 2
Below is my gatsby-config.js file
const path = require("path");
// Get paths of Gatsby's required rules, which as of writing is located at:
// https://github.com/gatsbyjs/gatsby/tree/fbfe3f63dec23d279a27b54b4057dd611dce74bb/packages/
// gatsby/src/utils/eslint-rules
const gatsbyRequiredRules = path.join(
process.cwd(),
"node_modules",
"gatsby",
"dist",
"utils",
"eslint-rules"
);
module.exports = {
siteMetadata: {
title: `########`,
description: `################`,
author: `###################`,
siteUrl: `###############`,
},
plugins: [
`gatsby-plugin-image`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
// This will impact how browsers show your PWA/website
// https://css-tricks.com/meta-theme-color-and-trickery/
// theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-wordpress`,
options: {
url: `http://34.133.115.37/graphql`,
},
},
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [`Poppins`],
display: `swap`,
},
},
{
resolve: `gatsby-plugin-styled-components`,
options: {
// Add any options here
},
},
{
resolve: "gatsby-plugin-eslint",
options: {
// Gatsby required rules directory
rulePaths: [gatsbyRequiredRules],
// Default settings that may be ommitted or customized
stages: ["develop"],
extensions: ["js", "jsx", "ts", "tsx"],
exclude: ["node_modules", "bower_components", ".cache", "public"],
// Any additional eslint-webpack-plugin options below
// ...
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
I don't know but probably my query is request is wrong, I have tried every can some help
wpMediaItem is not the same node as wpMediaItems (spot the trailing S). The first one is querying a single node, which by default would be sorted by upload date, while wpMediaItems fetch for all images, an array of images (edges in this case), that's why you can get edges in one query and an isolated node in the other, directly accessing for that node data (altText, etc.).
Take a deeper look at the GraphiQL playground (http://localhost:8000/___graphql) to get the correct node, but it should be there.

$multiply function not working in R studio

this is my code chunk
db.collection.aggregate([
{
"$unwind": "$items"
},
{
"$group": {
"_id": "$_id"
}
},
{
"$addFields": {
"total": {
"$multiply": [
"$items.quantity",
"$items.price"
]
}
}
},
{
"$limit": 10
}
])
This is what it outputs
This is a sample document
The problem you're facing is due to your $group stage. it works similar to SQL's groupby if you're more familiar.
What this means is that the quantity and price field are lost during that stage. you'll have to modify it a little to retain them.
I'm not sure exactly what you're trying to achieve as you did not specify but here is a toy example of what I imagine you're looking for:
db.collection.aggregate([
{
"$unwind": "$items"
},
{
"$group": {
"_id": "$items.name",
quantity: {
$sum: "$items.quantity"
},
price: {
$first: "$items.price"
}
}
},
{
"$addFields": {
"total": {
"$multiply": [
"$quantity",
"$price"
]
}
}
},
{
$sort: {
total: -1
}
},
{
"$limit": 10
}
])
Mongo Playground

Update state that has object with multiple keys

I have a state that looks like this:
{
id1: { houses: { name: 'x' }, cars: {} },
id2: { houses: { name: 'x' }, cars: {} },
...
}
I want to return a state that looks like this:
{
id1: { houses: {}, cars: {} },
id2: { houses: {}, cars: {} },
...
}
That is, I empty the houses entry. I don't know how to do that in an immutable reducer way, given the fact that the state can have many entries (id1, id2, id3,..)
Tricky, but the way I would try to do it is with Object.entries and .reduce
const originalObj = {
id1: { houses: { name: 'x' }, cars: { dontTouch: 'me1'} },
id2: { houses: { name: 'x' }, cars: { dontTouch: 'me2'} },
id3: { houses: { name: 'x' }, cars: { dontTouch: 'me2'} }
};
const initalValue = {};
const objWithResetHouses =
Object.entries(originalObj)
.reduce((acc, [propName, value]) => {
// "copy" every property, then write over "houses" with an empty object
acc[propName] = {...value, houses: {}};
return acc;
}, initalValue);
console.log(objWithResetHouses);

Can't update Array of objects

I'm trying to create an array of objects using simple-schema. In this example, a person has a careerHistory object that is filled with individual positions. I can't figure out how to insert and update the array of objects. It just errors. The only way I can get it to work is to be explicit, eg. 'careerHistory.position.1.company'.
I'm using:
meteor
simple-schema
reactjs
collection2-core
Path: mongodb
const ProfileCandidateSchema = new SimpleSchema({
userId: {
type: String,
regEx: SimpleSchema.RegEx.Id
},
careerHistory: { type: Array, optional: true },
'careerHistory.position': { type: Object, optional: true },
'careerHistory.position.$': { type: Object, optional: true },
'careerHistory.position.$.company': { type: String, optional: true },
'careerHistory.position.$.title': { type: String, optional: true }
});
Path: updateForm.js
ProfileCandidate.update(id, { $set: {
'careerHistory.position.company': this.state['position.company'],
'careerHistory.position.title': this.state['position.title'],
}
});
If you want to push object to array do
ProfileCandidate.update(id,
{ $push: { careerHistory: { position: {
'company': this.state['position.company'],
'title': this.state['position.title'],
}}}
});
if you want to update particular object
ProfileCandidate.update({ _id: id, 'careerHistory.position.company': this.state['position.company'] }, { $set: {
'careerHistory.position.$.title': this.state['position.title'],
}
});
see $ in set

kendo grid with java.util.Date doesn't work

I have a kendo grid with data being populated using ajax request.
the model returned from the controller has a java.util.Date field called someDate and the returned data in json for that field is like
{"total":3,
"data":[
{"someDate":1433116800000,"someValue":111.00},
{"someDate":1444116800000,"someValue":222.00},
{"someDate":1455116800000,"someValue":333.00}]}
The dataSouce is as below:
"dataSource": {
"schema": {
"total":"total",
"data":"data"
},
"transport":{
"parameterMap":function parameterMap(options, operation) {
if(operation==="read"){
return JSON.stringify(options);
} else {
return JSON.stringify(options.models);
}
},
"read":{
"dataType":"json",
"contentType":"application/json",
"type":"POST",
url : "${ajaxGetData}&param="+someParam
}
}
columns in the grid is like this
"columns":
[{
"field":"someValue",
"title":"Some Value",
"type":"numeric"
},{
"field":"someDate",
"title":"Date",
"type":"date",
format:"{0:yyyy-MM-dd hh:mm:ss tt}"
}
The issue is that the date and time is not displayed properly. If I use a template, I have to remove the "type":"date" for it to work however the filters don't work properly.
template:'#= kendo.toString( new Date(someDate), "yyyy/MM/dd hh:mm:ss tt") #'
How to show Date in a specific format "yyyy/MM/dd hh:mm:ss tt".
This JS Fiddle might help (but doesn't have the exact json structure with data and total)
Would it be possible to use ISO 8601 format for you dates, if that's possible the type date in the model definition should work (if you're using GSON library take a look here)
edit
According to the comments you can make use of the schema.parse, a sample of this using your provided fiddle will look like this:
var grid = $("#grid").kendoGrid({
dataSource: {
data: createRandomData(10),
schema: {
model: {
fields: {
FirstName: { type: "string" },
LastName: { type: "string" },
City: { type: "string" },
Title: { type: "string" },
BirthDate: { type: "date" },
Age: { type: "number" }
}
},
parse: function(response) {
var products = [];
for (var i = 0; i < response.length; i++) {
response[i].BirthDate = new Date(response[i].BirthDate);
}
return response;
}
},
pageSize: 10
},
height: 500,
scrollable: true,
sortable: true,
selectable: true,
change:onChangeSelection,
filterable: true,
pageable: true,
columns: [
{
field: "FirstName",
title: "First Name"
},
{
field: "LastName",
title: "Last Name"
},
{
field: "City"
},
{
field: "Title"
},
{
field: "BirthDate",
title: "Birth Date",
//template: '#= kendo.toString(BirthDate,"MM/dd/yyyy") #'
},
{
field: "Age"
}
]
}).data("kendoGrid");
I hope it works.

Resources