Node.js Firestore Query Select List of field paths - javascript

I try to create and returns a new Query instance that applies a field mask to the result and returns only the specified subset of fields.
When i use :
let query = firestore.collection('col').select('field1','field2','field3').get() ...
it's ok, the query returns all the collection documents with only the 3 specified fields.
In my context application, the specified fields list is on a configuration document. When i use :
let fieldsList = ['field1','field2','field3'];
let query = firestore.collection('col').select(fieldsList).get() ...
i have an error message "Argument at index 0 is not a valid FieldPath ..."
On the Google documentation, it is specified "You can specify a list of field paths to return"
So, i don't know how to pass a list of field paths to the query select method.
Many thanks for your help !!!

You are working on what is known as spread syntax.
To make it work, it need to add triple dots in front of fieldList:
let query = firestore.collection('col').select(...fieldsList).get() ..

Related

Array value Passing into SQL Server IN Query

I am using Nodejs Typescript and SQL Server.
I wrote query to find array matching values from database. If I pass static array values then data is fetching. When add dynamic array values query is not executing.
My query is below.
SELECT Name,id,date FROM venue where name IN('Bangalore','Delhi')
below query is not executing
let input = ["Bangalore","Delhi"]
SELECT Name,id,date FROM venue where name IN('${input}')
What I observed is When I pass dynamic values into query its taking "" quotes ie "Bangalore","Delhi" But query is expecting is single quotes ''
I know In Nodejs we can pass ? and values as parameter but in our case we using typescript and sequelize it has limitation. I unable to use that format.
You need to use array#map to create quoted city name which will be passed inside IN clause.
const input = ["Bangalore","Delhi"],
query = `SELECT Name,id,date FROM venue where name IN (${input.map(city => `'${city}'`)})`;
console.log(query);
May be the values inside IN clause is passing as an array. Please take a look at this array value passing inside IN clause

Node.js DB2 query with parameters

I am using node.js to connect to a DB2 database and loading different queries. But I would like to use parameters from user input.
My connection string is:
var ibmdb = require("ibm_db")
, cn = "DATABASE=namedb;HOSTNAME=hst;UID=portal;PWD=portalpwd;PORT=50000;PROTOCOL=TCPIP;"
;
But my query is static, I need to pass parameters/variables from user input.
I am using user input with var rl = require('readline'); but the problem now is how to communicate variables to this query and put dynamic parameters not a single value like name, id etc.
var rows = conn.querySync(
"select name,id,uid,password,type from db21.rep_name fetch first 10 rows only"
);
The Node.js package ibm_db is fully documented. There are several ways you could solve the problem, depending on whether you want to have the async or sync version and whether you want to first prepare, then execute the statement.
The simplest option probably is to use querySync as already done by you. There is an optional parameter bindingParameters to pass in an array of values. Those are bound to all places having a ?. Something like the following should work.
var rows = conn.querySync(
"select name,id,uid,password,type from db21.rep_name where name=? fetch first 10 rows only", ['henrik']
);

How can I check field exist or not in mongo db before querying to mongodb?

I have to run a dynamic query on collections in such a way that user enters collection name, field name and field value and I have to first of all check whether the field name supplied by user exists in the collection , if not then I have to run another query as shown in the example below.
For example:
If user enters collection name user, field name is type and field value is article. And based on parameters I have to query as follows:
1) If type field exists in collection user, my query will be:
query = user.find({type:'article'})
2) If type is not field of collection user, my query will be:
query = user.find()
I tried $exists but it is not working for me. And how can I use $exists before querying? because my collection, field name and field value all are dynamic.
And How can I check that type field exists or not in user collection?
I already tried the solution with $exists, but I want to know if there is another way to do it.
As #Philipp mentioned in his comment, you are bound to bump into performance issues as you would need to perform a full-collection scan without the use of indexes. Using $exists, the query will return fields also equal to null. Suppose you want to first find all records who have the field type set and isn't null, then use a combination of the $ne operator. The closest you could try is get the count of that field and then determine the query object based on the field count:
var type_count = db.user.find({"type": {$exists: true, $ne: null}}).count();
var query = (type_count > 0) ? {"type": "article"} : {};
db.user.find(query);

Breeze - Getting All Navigation Properties For Array of Entities

I'm trying to figure out with Breeze how to expand a specific navigation property for all items in an array of entities with a single request.
On this page of the Breeze documentation it shows the following way of achieving this:
var orderEntityType = selectedOrders[0].entityType;
var navProp = orderEntityType.getNavigationProperty("OrderDetails");
var navQuery = EntityQuery
.fromEntityNavigation(selectedOrders, navProp)
.expand("Product");
manager.executeQuery(navQuery).fail(handleFail);
However, when I tried this I get the error
The 'entity' parameter must be an entity
So I looked up in the documentation specifically for the EntityQuery.fromEntityNavigation method and it shows:
// 'employee' is a previously queried employee
var ordersNavProp = employee.entityType.getProperty("Orders");
var query = EntityQuery.fromEntityNavigation(employee, ordersNavProp);
The documentation indicates that it is for a specific entity, not multiple. Which is consistent with the error I'm getting.
Is it possible to get all the navigation properties in a single request, or is the preferred way to iterate over an array making a request for each entity?
Basically, I'm working on filtering a list of items. My goal is that when a user selects a filter it then expands the needed navigation property at that time instead of loading all the data up front.
Thanks for the help.
I think this might be a typo or some out of date information on the navigation properties documentation page. According to the API documentation for EntityQuery.fromEntityNavigation, the first parameter should be a single entity, not an array. Took a look at the breeze code, didn't see any evidence that an array of entities could be passed.
As a workaround, you could construct the query a bit differently. Continuing with the Order/OrderDetails scenario, you could do something like this:
var subsetOfOrders = ..., // array containing the subset of orders whose OrderDetails we need to load
predicates = subsetOfOrders.map(function(order) { return new breeze.Predicate('OrderId', '==', order.OrderId()); }),
predicate = breeze.Predicate.or(predicates),
query = new breeze.EntityQuery('Orders').expand('OrderDetails').where(predicate);
manager.executeQuery(query)...
If you're able to query the order details directly you don't even need expand. Breeze will wire up the freshly loaded OrderDetails to the respective orders entities that are already cached in the entity manager:
var subsetOfOrders = ..., // array containing the subset of orders whose OrderDetails we need to load
predicates = subsetOfOrders.map(function(order) { return new breeze.Predicate('OrderId', '==', order.OrderId()); }),
predicate = breeze.Predicate.or(predicates),
query = new breeze.EntityQuery('OrderDetails').where(predicate);
manager.executeQuery(query)...
This predicate based workaround may or may not be feasible depending on the number of orders you're dealing with. Could end up with a long query string. You could then consider using a dedicated controller action (ie "OrderDetailsByOrderId(int[] orderIds)" and use the withParameters EntityQuery method to load the order details using the new action.
The documentation was in error. I just corrected it.
#Jeremy Danyow offered a superb explanation and a solution. I probably would use his approach to solve a specific use case.
The documentation now discusses the problem and describes yet another approach that might be more appropriate if you were trying to write a general utility.
// create an array of filter criteria (`wherePredicate`) for each order
var predicates = orders.map(function (order) {
return EntityQuery.fromEntityNavigation(order,'OrderDetails')
.wherePredicate;
});
// OR the predicates together
var filter = breeze.Predicate.or(predicates);
EntityQuery.from('OrderDetails')
.where(filter)
.expand('Product')
.using(em).execute().catch(handleFail);
Thanks to you both for identifying the problem and working through it.

SuiteScript: How does the dynamic mode of nlobjColumn.setURL work?

In NetSuite, I have a scripted search of transactions that is expected to return results of several different transaction types. The results are then rendered in an nlobjList. I would like one of the columns of said list to be a link to the transaction that the list row represents.
In all NetSuite examples, this is accomplished something like:
var column = list.addColumn('number', 'text', 'Number', 'left');
column.setURL(nlapiResolveURL('RECORD','salesorder'));
column.addParamToURL('id','id', true);
Unfortunately, transaction is not an acceptable record type to pass to nlapiResolveURL, so I would need to dynamically detect the record type for each row. The setURL function does accept a second Boolean parameter that makes it dynamic per row, but I am not sure how this actually works. There are no examples, and the JSDocs do not explain its usage.
Does anyone have any guidance on generating a list with dynamic URLs in NetSuite?
If you set the dynamic argument to true, then the first argument should be a column listed in the data source that will contain the base URL.
column.setURL('base_url', true);
column.addParamToURL('id','id', true);
Then, on each record of your results, make sure you have a base_url that is set to the url you are looking for.
Note, the following example assumes a regular javascript object instead of the search result object.
rec.base_url = nlapiResolveURL('RECORD', rec.type)
Transaction field is just an abstraction for all transaction types. You can search them but can't load them.
The field you need to retrieve is recordtype. Sample code is below.
var recs = nlapiSearchRecord('transaction',null,null,new nlobjSearchColumn('recordtype'));
for(var i in recs)
url = nlapiResolveURL('RECORD',recs[i].getValue('recordtype'));

Categories

Resources