React Native JSON Array as Parameter to LINQ Contains - arrays

I want to get a list of people that have the same tags as the user.
For that I need to use a react native fetch and the entity framework.
I also tried some raw sql with EF, but couldn't make it work, just don't know how.
I have two fetches. Both return a typical JSON object array. So I'm doing this:
var users = db.Users
.Include("TagUsers")
.Where(u => u.TagUsuario.Any(t => tags.Contains(t.idTag))).ToList();
The tags variable is an object array from a React Native Fetch, which in my C# function is of the type IList<>long.
The problem is that if this array have one element, like this const tags = [1]; or from the fetch like this
{0}
Tags:
idTag: 1
Name: "MyTag"
I can return the people with this tag, but if I do like this const tags = [1, 2]; or
{0}
Tags:
idTag: 1
Name: "MyTag"
{1}
Tags:
idTag: 2
Name: "AnotherTag"
It returns nothing on my LINQ request.
But if I do something like this on my C# function:
IList<>long tags = new List<>long();
tags.Add(1);
tags.Add(2);
It works perfectly.
The problem here is that the object array from the fetch is not "compatible" with the LINQ statement (Any, Contains). So I am in search of an alternative.
What do I have to do?
Change the IList parameter? I'm using that because accepts null without crashing.
Change the LINQ?
Use Raw SQL?
Maybe some conversion to get only an int array with the tags, not an object one.
Thanks for any tips and solutions.

Can you try to get the idTags from tags and use it as below.
var idTags = tags.Select(t => t.idTag);
var users = db.Users
.Include("TagUsers")
.Where(u => u.TagUsuario.Any(t => idTags.Contains(t.idTag))).ToList();

Related

Cannot return documents based off a sorted index using Fauna DB

I'm bumbling my way through adding a back-end to my site and have decided to get acquainted with graphQL. I may be structuring things totally the wrong way, however from following some tutorials I have a React front-end (hosted on Vercel), so I have created an api folder in my app to make use of Vercel's serverless functions. I'm using Apollo server and I decided to go with Fauna as my database.
I've successfully been able to return an entire collection via my API. Now I wish to be able to return the collection sorted by my id field.
To do this I created an index which looks like this:
{
name: "sort_by_id",
unique: false,
serialized: true,
source: "my_first_collection",
values: [
{
field: ["data", "id"]
},
{
field: ["ref"]
}
]
}
I then was able to call this via my api and get back and array, which simply contained the ID + ref, rather than the associated documents. I also could only console log it, I assume because the resolver was expecting to be passed an array of objects with the same fields as my typedefs. I understand I need to use the ref in order to look up the documents, and here is where I'm stuck. An index record looks as follows:
[1, Ref(Collection("my_first_collection"), "352434683448919125")]
In my resolvers.js script, I am attempting to receive the documents of my sorted index list. I've tried this:
async users() {
const response = await client.query(
q.Map(
q.Paginate(
q.Match(
q.Index('sort_by_id')
)
),
q.Lambda((ref) => q.Get(ref))
)
)
const res = response.data.map(item => item.data);
return [... res]
}
I'm unsure if the problem is with how I've structured my index, or if it is with my code, I'd appreciate any advice.
It looks like you also asked this question on the Fauna discourse forums and got an answer there: https://forums.fauna.com/t/unable-to-return-a-list-of-documents-via-an-index/3511/2
Your index returns a tuple (just an array in Javascript) of the data.id field and the ref. You confirmed that with your example result
[
/* data.id */ 1,
/* ref */ Ref(Collection("my_first_collection"), "352434683448919125")
]
When you map over those results, you need to Get the Ref. Your query uses q.Lambda((ref) => q.Get(ref)) which passes the whole tuple to Get
Instead, use:
q.Lambda(["id", "ref"], q.Get(q.Var("ref")))
// or with JS arrow function
q.Lambda((id, ref) => q.Get(ref))
or this will work, too
q.Lambda("index_entry", q.Get(q.Select(1, q.Var("index_entry"))))
// or with JS arrow function
q.Lambda((index_entry) => q.Get(q.Select(1, index_entry)))
The point is, only pass the Ref to the Get function.

Best approach in moving data from one array to a new array in angular ts

.subscribe((dataChart) => {
// console.log(dataChart)
var forxaxis = []
var cd = [dataChart]
// console.log(cd)
cd.forEach(element => {
forxaxis.push(element.strRequestDate)
console.log(forxaxis)
});
},
Im trying to move my data in the first array into a new array so that I can use it with chart.js. but it didnt work.
dataChart contain 2 column of data. i insert dataChart into an array called cd. then i tried to push one of the column from dataChart which is called strRequestDate into a new array called forxaxis but it just didnt work as per expected. the result is as shown in the image attached.
this is how the data look like. it was called by using sharepoint API
error and the data
You can use array.map property here, so you don't need to push data manually from one array to another
I have taken sample data in dataChart array for demonstration purpose only.
let dataChart = [{strRequestId: 1, strRequestDate: 'ABC'}, {strRequestId: 1, strRequestDate: 'PQR'}];
let forxaxis = dataChart.map(x => x.strRequestDate);
console.log(forxaxis);
Demo
Output:

discord.js import .json values into variable

I have these values stored in a .json as a very basic xp system (im aware of corruption issues, like to learn json before moving to db)
"267752827723492576":{"xp":308,"level":1}, "267752827723492576":{"xp":308,"level":1}
i want to import userid, xp, and level into a variable so i can make a leaderboard command, i already have working code for doing the comparison and sorting (below) . "user" being the variable containing my data from the json file
var users = {
"":{"xp":0,"level":0},
"":{"xp":0,"level":0},
"":{"xp":0,"level":0},
"":{"xp":0,"level":0},
"":{"xp":0,"level":0},
};
let board = Object.entries(users)
.map(([key, val]) => ({id: key, ...val}))
.sort((a, b) => b.xp- a.xp);
console.log(board);
Post is not clear, but you just wan't to import json?
const users = require("path_to.json")
You can also use fs.readFile alongside JSON.parse
Also instead of using an object to store the data you can use an array
with this format: (same format after you used your map method)
[{ id: "", xp: 200, level: 2}]
For preformance both have ups and downs, for actually getting a user by id an object is probably faster, but since you have to use Object.entries and map it probably evens out
Incase you do switch to array, here's how you would fetch a user
// ... just stands for data here, not the deconstructing or rest syntax
const json = [{...}, {...}];
const user = json.find(f => f.id === "the-id-here");

Firestore to query by an array's field value

I'm trying to run a simple query, where I search for a document that contains a value inside an object array.
For instance, look at my database structure:
I want to run a query similar to this:
db.collection('identites').where("partyMembers", "array-contains", {name: "John Travolta"})
What is the correct way to achieve this, is it even possible with Firestore?
Thanks.
As Frank has explained in his answer it is not possible, with array-contains, to query for a specific property of an object stored in an array.
However, there is a possible workaround: it is actually possible to query for the entire object, as follows, in your case:
db.collection('identites')
.where(
"partyMembers",
"array-contains",
{id: "7LNK....", name: "John Travolta"}
)
Maybe this approach will suit your needs (or maybe not....).
The array-contains operations checks if an array, contains a specific (complete) value. It can't check if an array of objects, contains an item with a specific value for a property.
The only way to do your query, is to add an additional field to your document with just the value you want to query existence on. So for example: partyMemberNames: ["John Travolta", "Olivia Newton"].
If you want to extract name: "John Travolta" from "partyMembers" array in a document. you can achieve this by some similar approach in which you can loop through all arrays in a document to find this name.
const [names, setNames] = React.useState([])
const readAllNames = async() => {
const snapshot = await firebase.firestore().collection('identites').doc(documentID).get()
const filterData = snapshot.data().question.map(val => val.name === "John Travolta" ? val : null)
setNames( filterData.filter(e=>e) );
}
This technique is used in perticular Document as we are giving .doc(documentID) This way you can get all the arrays having name: "John Travolta" in names constant.

Issue with .populate() on array of arrays in Mongoose Model [duplicate]

In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as
Person.find({})
.populate('books movie', 'title pages director')
.exec()
However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:
Person.find({})
.populate('books', 'title pages')
.populate('movie', 'director')
.exec()
which gives me the expected result and queries.
But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.
After looking into the sourcecode of mongoose, I solved this with:
var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
Person.find({})
.populate(populateQuery)
.execPopulate()
you can also do something like below:
{path:'user',select:['key1','key2']}
You achieve that by simply passing object or array of objects to populate() method.
const query = [
{
path:'books',
select:'title pages'
},
{
path:'movie',
select:'director'
}
];
const result = await Person.find().populate(query).lean();
Consider that lean() method is optional, it just returns raw json rather than mongoose object and makes code execution a little bit faster! Don't forget to make your function (callback) async!
This is how it's done based on the Mongoose JS documentation http://mongoosejs.com/docs/populate.html
Let's say you have a BookCollection schema which contains users and books
In order to perform a query and get all the BookCollections with its related users and books you would do this
models.BookCollection
.find({})
.populate('user')
.populate('books')
.lean()
.exec(function (err, bookcollection) {
if (err) return console.error(err);
try {
mongoose.connection.close();
res.render('viewbookcollection', { content: bookcollection});
} catch (e) {
console.log("errror getting bookcollection"+e);
}
//Your Schema must include path
let createdData =Person.create(dataYouWant)
await createdData.populate([{path:'books', select:'title pages'},{path:'movie', select:'director'}])

Resources