Exact field input mongoose for nodejs - regex

I've recently been attempting to pull my hair out getting stuck on what I would call a trivial issue.
The way mongoose in nodejs handles the specific field inputs. I have a specific issue where mongoose is not doing the same as mongodb is doing.
The issue is the following, if I use a "-" symbol in my field name, mongoose seems to run some weird operation on it, instead of accepting it as part of a string.
I've tried running several regex commands, some / escapes, however it should literally just take the input, as I know the specific data I'm looking for.
The code causing the issue is the following:
datapoints.find({type: "charging-type", device: device._id})
.exec(function(err, objects){
if(!objects){
log("Can't find objects");
}
});
Going straight into mongo shell and typing:
db.datapoints.count({type: "charging-type", device: device._id})
taking out the type makes everything work, changing the type to for example: shuntvoltage, current, ... all work perfectly.
The problem thus occurs with the usage of this - symbol.
What would be the way to enter this inputstring with a special character as an exact string?
Any help would be much appreciated.
Edit as per request; I don't get any error, I get objects==undefined (or !objects), schema is below.
var datapointSchema = mongoose.Schema({
type: { type: String, lowercase: true},
value: { type: Number},
timestamp: { type: Number},
device: { type: ObjectId, ref: "devices"}
});
module.exports = mongoose.model('datapoints', datapointSchema)

Manually updated the field in mongodb from charging-status to chargingstatus, as no useful answer was produced.
It's a workaround and should be considered unresolved.
Final code ended up looking as such:
var cursor = calcpoints.find({device: device._id}).where('type').equals('chargingstatus').sort({timestamp: 1}).cursor();

Related

Create Inventory Adjustment giving an error

I am trying to create an inventory adjustment from a MAP/REDUCE script. the record from which i am setting the values is getting ftom a search in getInputData(). In map function i am loading that custom record and setting these values
var newcase_inv_Adj = record.create({type:'inventoryadjustment',isDynamic:true});
newcase_inv_Adj.setValue({fieldId:'account',value:creel_account});
newcase_inv_Adj.setValue({fieldId:'custbody_cp_adjreasoncode',value:creel_reasoncode});
newcase_inv_Adj.setValue({fieldId: 'custbody_c_from', value: name});
newcase_inv_Adj.selectNewLine({sublistId:'inventory'});
newcase_inv_Adj.setCurrentSublistValue({sublistId:'inventory',fieldId:'item',value:creel_item});
newcase_inv_Adj.setCurrentSublistValue({sublistId:'inventory',fieldId:'location',value:creellocation});
newcase_inv_Adj.setCurrentSublistValue({sublistId:'inventory',fieldId:'adjustqtyby',value:creel_weigh_oh});
var create_inv_detail = newcase_inv_Adj.getCurrentSublistSubrecord({sublistId: 'inventory',fieldId: 'inventorydetail'});
create_inv_detail.selectNewLine({sublistId:'inventoryassignment' });
create_inv_detail.setCurrentSublistValue({sublistId:'inventoryassignment',fieldId:'receiptinventorynumber',value: creel_casenumber});
create_inv_detail.setCurrentSublistText({sublistId:'inventoryassignment',fieldId:'binnumber',value: creel_bin });
create_inv_detail.setCurrentSublistValue({sublistId:'inventoryassignment',fieldId:'quantity',value: creel_weigh_oh });
create_inv_detail.commitLine('inventoryassignment');log.debug("N","commited inventoryassignment");
newcase_inv_Adj.commitLine({sublistId:'inventory'});log.debug("N","commited inventory");
var invAdjID = newcase_inv_Adj.save();log.debug("N","invAdjID : "+invAdjID);
But, I am getting this error as {"type":"error.SuiteScriptError","name":"UNEXPECTED_ERROR"
Is it because of Map/Reduce script?
I don't find anything wrong in the code.
Few suggestions:
- Follow the sequence: Set subsidiary value before you setvalue for account or any other mandatory field.
- First try with inventory items without serial numbers and see if you continue to face same problem.
- You need to make sure you all your variables has valid value (not null or undefined).
- First try doing this in a schedule script.

React Native SectionList has incomprehensible flow type error

If have this simple SectionList definition in my code:
const s = (
<SectionList
renderItem={({ item }) => <Text>abc</Text>}
renderSectionHeader={({ section }) => <Text>abc</Text>}
sections={[{ data: [1, 2, 3], title: 'abc' }]}
/>
);
And flow generates this error message which refers to the whole "tag block" (it is actually copy pasted from VSCode):
[flow] props of React element `SectionList` (This type is incompatible with See also: React element `SectionList`)
What is happening here?
EDIT I am using
flow-bin: 0.56.0
react: 16.0.0
react-native: 0.49.1
EDIT2 So the example can be reduced to this simple line (without impacting the error message):
<SectionList sections={[]} />;
EDIT3 I just discovered that flow complains about several types that are defined in the React Native library (mainly about missing type arguments for generic types). I am wondering if I should use an older flow-bin version. Is there a compatibility table for React Native and flow?
I had a similar problem with react-native: 0.49.3 and flow-bin: 0.53.0. After checking the type definitions from the SectionList source, got it to work without type warnings as follows:
type Row = {
name: string,
}
type Section = {
title: string,
data: $ReadOnlyArray<Row>,
}
const mySections: $ReadOnlyArray<Section> = [...] // your data here
<SectionList sections={mySections} />
So the key for me was to use $ReadOnlyArray<T> instead of Array<T>. Perhaps this helps you!
React has a built in Flow type for sections called SectionBase:
import type { SectionBase } from 'react-native/Libraries/Lists/SectionList'
type Section = SectionBase<DataType>
So based on what Martin answered you would write: SectionBase<Row>
The OP's code should have gotten no complaints from Flow as it is valid.
I had a related issue in that I was using a state that held sections and I could not find the right type for Flow. I could not use SectionBase directly since it did not have the extra title property I needed. I solved it by using an intersection type:
type Section = { title: string } & SectionBase<ScheduleChange>
type State { sections: Section[] }
...
<SectionList
sections = this.state.sections
...
/>
interface SectionDataModel {
...
}
const [sections, setSections] = useState<ReadonlyArray<SectionDataModel> | []>([])
This worked for me

Unparsable MOF Query When Trying to Register Event

Update 2
I accepted an answer and asked a different question elsewhere, where I am still trying to get to the bottom of this.
I don't think that one-lining this query is the answer, as I am still not getting the required results (and multi-lining queries is allowed in .mof, as shown in the URLs in comments to the answer ...
Update
I rewrote the query as a one-liner as suggested, but still got the same error! As it was still talking about lines 11-19 I knew there must be another issue. After saving a new file with the change, I reran mofcomp and it appears to have loaded, but the event which I have subscribed to simply does not work.
I really feel that there is not enough documentation on this topic and it is hard to work out how I am meant to debug this - any help on this would be much appreciated, even if this means using a different more appropriate method.
I have the following .mof file, which I would like to use to register an event on my system :
#pragma namespace("\\\\.\\root\\subscription")
instance of __EventFilter as $EventFilter
{
Name = "Event Filter Instance Name";
Query = "Select * from __InstanceCreationEvent within 1 "
"where targetInstance isa \"Cim_DirectoryContainsFile\" "
"and targetInstance.GroupComponent = \"Win32_Directory.Name=\"c:\\\\test\"\"";
QueryLanguage = "WQL";
EventNamespace = "Root\\Cimv2";
};
instance of ActiveScriptEventConsumer as $Consumer
{
Name = "TestConsumer";
ScriptingEngine = "VBScript";
ScriptText =
"Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
"Set objFile = objFSO.OpenTextFile(\"c:\\test\\Log.txt\", 8, True)\n"
"objFile.WriteLine Time & \" \" & \" File Created\"\n"
"objFile.Close\n";
// Specify any other relevant properties.
};
instance of __FilterToConsumerBinding
{
Filter = $EventFilter;
Consumer = $Consumer;
};
But whenever I run the command mfcomp myfile.mof I am getting this error:
Parsing MOF file: myfile.mof
MOF file has been successfully parsed
Storing data in the repository...
An error occurred while processing item 1 defined on lines 11 - 19 in file myfile.mof:
Error Number: 0x80041058, Facility: WMI
Description: Unparsable query.
Compiler returned error 0x80041058
This error appears to be caused by incorrect syntax in the query, but I don't understand where I have gone wrong with this - is anyone able to advise?
There are no string concatenation or line continuation characters being used in building "Query". To keep it simple, you could put the entire query on one line.

error with RegExp inside angular.toJson

I'm trying to do a 'like' query in mongodb. I see that's done with a regexp so I'm trying to set it like this:
$scope.clients = Client.query({
q:angular.toJson({
name: RegExp($routeParams.str)
})
});
The thing is angular.toJson function does not get any regexp:
http://plnkr.co/edit/idXMT1
Is there any other way to do that?
From my understanding of your question, you want your JSON object to contain the regular expression as a string?
In that case, you can manually convert it to a string in the declaration, i.e:
$scope.object = angular.toJson({
"param" : new RegExp(str).toString()
});
See updated plunk:
http://plnkr.co/edit/yLogI8
I finally found a solution.
The problem is using the toJon function as it does not allow any key starting with / or $ so the solution is avoiding the use of this function and just write the object as a string
$scope.clients = Client.query({
q:'{src:{$regex:"' + $routeParams.str + '"}}'
};

What's the standard pattern for ember-data validations? (invalid state, becameInvalid...)

I've kinda been struggling with this for some time; let's see if somebody can help me out.
Although it's not explicitly said in the Readme, ember-data provides somewhat validations support. You can see that on some parts of the code and documentation:
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/states.js#L411
https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/model/states.js#L529
The REST adapter doesn't add validations support on itself, but I found out that if I add something like this in the ajax calls, I can put the model on a "invalid" state with the errors object that came from the server side:
error: function(xhr){
var data = Ember.$.parseJSON(xhr.responseText);
store.recordWasInvalid(record, data.errors);
}
So I can easily to the following:
var transaction = App.store.transaction();
var record = transaction.createRecord(App.Post);
record.set('someProperty', 'invalid value');
transaction.commit()
// This makes the validation fail
record.set('someProperty', 'a valid value');
transaction.commit();
// This doesn't trigger the commit again.
The thing is: As you see, transactions don't try to recommit. This is explained here and here.
So the thing is: If I can't reuse a commit, how should I handle this? I kinda suspect that has something to do to the fact I'm asyncronously putting the model to the invalid state - by reading the documentation, it seems like is something meant for client-side validations. In this case, how should I use them?
I have a pending pull request that should fix this
https://github.com/emberjs/data/pull/539
I tried Javier's answer, but I get "Invalid Path" when doing any record.set(...) with the record in invalid state. What I found worked was:
// with the record in invalid state
record.send('becameValid');
record.set('someProperty', 'a valid value');
App.store.commit();
Alternatively, it seems that if I call record.get(...) first then subsequent record.set(...) calls work. This is probably a bug. But the above work-around will work in general for being able to re-commit the same record even without changing any properties. (Of course, if the properties are still invalid it will just fail again.)
this may seem to be an overly simple answer, but why not create a new transaction and add the pre-existing record to it? i'm also trying to figure out an error handling approach.
also you should probably consider writing this at the store level rather than the adapter level for the sake of re-use.
For some unknown reason, the record becomes part of the store default transaction. This code works for me:
var transaction = App.store.transaction();
var record = transaction.createRecord(App.Post);
record.set('someProperty', 'invalid value');
transaction.commit()
record.set('someProperty', 'a valid value');
App.store.commit(); // The record is created in backend
The problem is that after the first failure, you must always use the App.store.commit() with the problems it has.
Give a look at this gist. Its the pattern that i use in my projects.
https://gist.github.com/danielgatis/5550982
#josepjaume
Take a look at https://github.com/esbanarango/ember-model-validator.
Example:
import Model, { attr } from '#ember-data/model';
import { modelValidator } from 'ember-model-validator';
#modelValidator
export default class MyModel extends Model {
#attr('string') fullName;
#attr('string') fruit;
#attr('string') favoriteColor;
validations = {
fullName: {
presence: true
},
fruit: {
presence: true
},
favoriteColor: {
color: true
}
};
}