Record Id and Type coming as null when I get the result from a saved search in a suitscript - netsuite

I have a saved search already in my sandbox account.I am not sure on what record the saved search is created. I tried loading the saved search as :
var savedSearch = nlapiLoadSearch("item", searchId);
var resultset = savedSearch.runSearch();
resultset.getResults(0, 1000);//Actually I have looped and got all my search results.
When I run it on the debugger I get to see the results in the columns correctly, but I see the recordId and recordType of the savedsearch result is null. I want to have the recordtype, so that I can load that particular record as required.
Attached is a screenshot of the debugger results in variables section.

If the methods Eric mentions are returning nulls the your search is probably using aggregates like count and sum.
You can get internal id by including internal id as a group field and you can include type as a group field too but you can't use it directly like you can results[i].getRecordType()

nlobjSearchResult Objects have getId() and getRecordType() methods for this purpose.
For example, if you store your results in an Array called searchResults:
searchResults.forEach(printResult);
function printResult(result) {
var recordId = result.getId();
var recordType = result.getRecordType();
// ...
}

Related

ravendb NodeJS, load related document and create a nested result in a query

I have an index that returns something like this
Company_All {
name : string;
id : string;
agentDocumentId : string
}
is it possible to load the related agent document and then generate a nested result with selectFields and QueryData like this
ICompanyView {
companyName : 'Warner',
user {
documentId : 'A/1'
firstName : 'john',
lastName : 'paul'
}
}
I need something like the below query that obviously doesn't work as I expect:
const queryData = new QueryData(
["name", "agentDocumentId", "agent.firstName", "agent.lastName"],
["companyName", "user.documentId", "user.lastName", "user.firstName"]);
return await session.query<Company_AllResult>({ index: Company_All })
.whereEquals("companyId", request.companyId)
.include(`agents/${agentDocumentId}`) // ????
.selectFields(queryData,ICompanyView)
.single();
Yes, you can do that using:
https://ravendb.net/docs/article-page/5.4/nodejs/indexes/indexing-related-documents
This is called indexing related documents, and is accessible at indexing time, not query time.
Alternatively, you have the filter clause, which has access to the loaded document, but I wouldn't generally recommend doing this.
Generally:
When you query an index, the results of querying the index are the documents from the collection the index was defined on.
Index-fields defined in the index are used to filter the index-query
but the results are still documents from the original collection.
If you define an index that indexes content from a related-document then when making an index-query you can filter the documents by the indexed-fields from the related documents, but the results are still documents from the original collection.
When making an index-query (or any other query) you can project the query results so that Not the full documents of the original collection are returned but some other object.
Now:
To project/get data from the indexed related-document you have 2 options:
Store the index-fields from the related-document in the index.
(Store all -or- specific fields).
This way you have access to that content when making a projection in your query.
See this code sample.
Don't store the index-fields from the related-document,
then you will be able to use the index-fields to filter by in your query,
but to get content you will need to use 'include' feature in your query,
and then use the session.load, which will Not make another trip to the server.
i.e. https://demo.ravendb.net/demos/nodejs/related-documents/query-related-documents

GraphQl filter in list field

I'm working on GraphQL API, and I want to filter my data "Products" by sellerId knowing that a product can be sold by several sellers, which means the sellers' field is an array.
Here is the query:
query GetProducts($filterObject:ProductWhereInput!){
products(where:$filterObject){
id
name
description
sku
price
sellers(where:$filterObject.sellers){
id
firstname
lastname
}
images{
url
fileName
}
}
}
Filter variable is defined like that
{
"filter":{
"sellerId":"ckzia0llkfngz0d09mrppd7kh"
}
}
and when I execute this query I get the error
"message": "unknown field 'filterObject.sellers' in variables"
I'm not sure if that's the correct method to apply the filter, it worked for me when I use it for single-value fields, but not with arrays.
If someone could help me, I'll be thankful.
Here you defined $filterObject as a query variable
query GetProducts($filterObject:ProductWhereInput!)
But the way this line is written, it "uses" a variable that is not defined:
sellers(where:$filterObject.sellers)
It's looking for a variable named: "$filterObject.sellers", not a property "sellers" of $filterObject.
Possible solution 1 - server side:
You can change the sellers field definition to use the whole $filterObject and then the resolver function on the server can extract the field it needs.
sellers(where:$filterObject)
This solution makes sense if you have control over the server side.
Possible solution 2 - client side:
If you cannot change the code on the server side, you can define a separate variable and use it instead:
query GetProducts($filterObject:ProductWhereInput!, $filterSellersObject:ProductSellersWhereInput!){
//...
sellers(where:$filterSellersObject){
//...
(assuming ProductSellersWhereInput is a defined type)

Mongoose needs 2 times excecution to update collection

Something strange is going on or something idiotic I did but I got the following problem.
I got aenter code here web app where I have an online menu for a restaurant.
The structure of the products is as follows.
Facility->Category->Item->Name
So all item models have saved the name of the category they belong to as a string.
But sometimes you want to change the name of the category. What I wanted to do was find all the items in this category and change the name of the assigned category to the new one. Everything looked great until I saw that it took two times to run the controller that changed the name of the category and on the items to fully save the new name to the items.
The category changed the name but the items updated to the new name on the second run. Weird right?
So, what is that you can see that I don't and I implemented the silliest way of bugfix in the history of bugfixes.
Here is the controller - route.
module.exports.updateCtg = async(req,res)=>{
const {id} = req.params;
for(i=0;i<2; i++){
category = await CategoryModel.findByIdAndUpdate(id,{...req.body.category});
await category.save();
items = await ItemModel.find({});
for(item of items){
if(item.facility === category.facility){
item.category = category.name;
await single.save();
}
}
}
res.render('dashboard/ctgview', {category._id});
}
The findByIdAndUpdate function returns the found document, i.e. the document before any updates are applied.
This means that on the first run through category is set to the original document. Since the following loop uses category.name, it is setting the category of each item to the unmodified name.
The second iteration find the modified document, and the nested loop uses the new value in category.name.
To get this in a single pass, use
item.category = req.category.name;
or if you aren't certain it will contain a new name, use
item.category = req.category.name || category.name;
Or perhaps instead of a loop, use updateMany
if (req.category.name) {
ItemModel.updateMany(
{"item.facility": category.facility},
{"item.category": req.category.name}
)
}

Google Datastore can't update an entity

I'm having issues retrieving an entity from Google Datastore. Here's my code:
async function pushTaskIdToCurrentSession(taskId){
console.log(`Attempting to add ${taskId} to current Session: ${cloudDataStoreCurrentSession}`);
const transaction = datastore.transaction();
const taskKey = datastore.key(['Session', cloudDataStoreCurrentSession]);
try {
await transaction.run();
const [task] = await transaction.get(taskKey);
let sessionTasks = task.session_tasks;
sessionTasks.push(taskId);
task.session_tasks = sessionTasks;
transaction.save({
key: taskKey,
data: task,
});
transaction.commit();
console.log(`Task ${taskId} added to current Session successfully.`);
} catch (err) {
console.error('ERROR:', err);
transaction.rollback();
}
}
taskId is a string id of another entity that I want to store in an array of a property called session_tasks.
But it doesn't get that far. After this line:
const [task] = await transaction.get(taskKey);
The error is that task is undefined:
ERROR: TypeError: Cannot read property 'session_tasks' of undefined
at pushTaskIdToCurrentSession
Anything immediately obvious from this code?
UPDATE:
Using this instead:
const task = await transaction.get(taskKey).catch(console.error);
Gets me a task object, but it seems to be creating a new entity on the datastore:
I also get this error:
(node:19936) UnhandledPromiseRejectionWarning: Error: Unsupported field value, undefined, was provided.
at Object.encodeValue (/Users/.../node_modules/#google-cloud/datastore/build/src/entity.js:387:15)
This suggests the array is unsupported?
The issue here is that Datastore supports two kinds of IDs.
IDs that start with name= are custom IDs. And they are treated as strings
IDs that start with id= are numeric auto-generated IDs and are treated as integers
When you tried to updated the value in the Datastore, the cloudDataStoreCurrentSession was treated as a string. Since Datastore couldn't find an already created entity key with that custom name, it created it and added name= to specify that it is a custom name. So you have to pass cloudDataStoreCurrentSession as integer to save the data properly.
If I understand correctly, you are trying to load an Array List of Strings from Datastore, using a specific Entity Kind and Entity Key. Then you add one more Task and updated the value of the Datastore for the specific Entity Kind and Entity Key.
I have create the same case scenario as yours and done a little bit of coding myself. In this GitHub code you will find my example that does the following:
Goes to Datastore Entity Kind Session.
Retrieves all the data from Entity Key id=5639456635748352 (e.g.).
Get's the Array List from key: session_tasks.
Adds the new task that passed from the function's arguments.
Performs the transaction to Datastore and updates the values.
All steps are logged in the code and there are a lot of comments explaining exactly how the code works. Also there are two examples of currentSessionID. One for custom names and other one for automatically generated IDs. You can test the code to understand the usage of it and modify it according to your needs.

Mongoose - Check if each key of .findOne() doc is a ObjectId (referenced object)

I got a generic GET function that worps for my entire app, considering I am using just absolute documents.
Now I get to a point that I need some properties of some of my documents reference others, and when executed, the GET function populate them (obviously). For that, I need to require the referenced schema, and populate with referenced model.
The point is: I want to my GET function stay generic, so I don't want to reference any of my schemas, unless it is needed. The same goes for the .populate() method.
To achieve that, I am iterating through each key of the resulting object of the .findOne() method, and trying to check if each specific key, is or is not a ObjectId/reference or not. something like this:
require('../schemas/mySchema').findOne({'slug': req.params.slug}, function(err, doc){
console.log(mongoose.Types.ObjectId.isValid(doc[key]));
});
But the only true value it returns is for the "id"and "__v" properties (no idea where these came from... I did not set them. _id is also false), all the rest comes as false (including a given property that IS a reference, tested and working)
Is there any way to do that?
Thanks in advance
I believe mongoose returns references with the objectId nested - in the same structure as a populated object but having only the _id key. Try this:
var item = doc[key];
if (typeof item === 'object') {
console.log(mongoose.Types.ObjectId.isValid(item._id));
}

Resources