mongoose.findOneAndUpdate() changes the value being saved in my Express app - node.js

I found one other person asking about a value override, but its unanswered. Hopefully someone can point out the dumb thing im missing! Here's the gist...
var vote = req.body.vote;
var boolVote;
(vote === 'good') ? boolVote = true : boolVote = false;
// these square brackets were the issue ----------\/
Model.findOneAndUpdate({firstname:'Jane'},{$set:{'event.attempt.judge1':[boolvote]}},
{new: true},(err,lifter)=>{console.log(lifter.event.attempt.judge1})
Ive chopped it down to its basic function because in-program boolVote will console.log as the correct value (true if vote==='good', false otherwise) but no matter how i rearrange things it ALWAYS updates to the DB as true...
Originally boolVote was this
var boolVote = ()=>(vote === 'good') ? true : false;
which didnt work either. I can change the value in the mongo CLI without issue.
Has anyone else had issues saving a FALSE value to MongoDB? If so, what does it take to get this working, and if not what am i doing wrong???
Thanks in advance for any help, im pulling hair here.

You can write ternary simply like this, i'm not familiar with js but in other program languages like java the syntax is same as below
var boolVote = vote === 'good' ? true : false;
or
var boolVote = ( vote === 'good' ) ? true : false;
but when you do this
var boolVote = () => ( vote === 'good' ) ? true : false;
here boolVote is a Function with no arguments, so you need call boolVote() to get its value
EDIT
event.attempt.judge1 is a field, but when enclosed with square bracket as an array in the update method, regardless of true/false the non empty array resolved to true, same updated in db
Model.findOneAndUpdate(
{firstname:'Jane'},
{$set:{'event.attempt.judge1':boolvote}}, //removed []
{new: true},
(err,lifter)=>{console.log(lifter.event.attempt.judge1)}
)

Related

How can i simplify checking if a value exist in Json doc

Here is my scenario, i am parsing via javascript a webpage and then post the result to an restApi to store the json in a db. The code works fine as long as all fields i defined in my script are send. Problem is over time they website might change names for fields and that would cause my code to crash.
Originally i used code like this
const mySchool = new mls.School();
mySchool.highSchoolDistrict = data["HIGH SCHOOL DISTRICT"].trim();
mySchool.elementary = data.ELEMENTARY.trim();
mySchool.elementaryOther = data["ELEMENTARY OTHER"].trim();
mySchool.middleJrHigh = data["MIDDLE/JR HIGH"].trim();
mySchool.middleJrHighOther = data["MIDDLE/JR HIGH OTHER"].trim();
mySchool.highSchool = data["HIGH SCHOOL"].trim();
mySchool.highSchoolOther = data["HIGH SCHOOL OTHER"].trim();
newListing.school = mySchool;
but when the element does not exist it complains about that it can not use trim of undefined. So to fix this i came up with this
if (data["PATIO/PORCH"]) {
newExterior.patioPorch = data["PATIO/PORCH"].trim();
}
this works but i am wondering if there is a more global approach then to go and check each field if it is defined ?
You could leverage a sort of helper function to check first if the item is undefined, and if not, return a trim()-ed version of the string.
var data = Array();
data["HIGH SCHOOL DISTRICT"] = " 123 ";
function trimString(inputStr) {
return (inputStr != undefined && typeof inputStr == "string") ? inputStr.trim() : undefined;
}
console.log(trimString(data["HIGH SCHOOL DISTRICT"]));
console.log(trimString(data["ELEMENTARY OTHER"]));

SuiteScript 2 result set

I am writing a script in 2.0, here is the snippet.
var resultSet = [];
var result = search.load({
id:'customsearch_autosend_statement_invoice'
}).run().each(function( item ) {
resultSet.push(item);
});
If I run this saved search in the normal interface I get lots of rows like 2000 plus, but if I run this code I get back 1 row, even using the each function and adding the items to another array I only get one row. I don't see anything in the documentation about this. Can anyone tell me why this is? I'm stumped. thanks in advance for any help
I found the answer but not because I should have seen it, the examples don't make any attempt to tell you that you have to return true from the each method in order to keep receiving rows. So the answer is that at the end of the "each" function you must return a true value to receive the next row. Like this, so thanks for your effort if I miss your post.
var resultSet = [];
var result = search.load({
id:'customsearch_autosend_statement_invoice'
}).run().each(function( item ) {
resultSet.push(item);
return true;
});
It's detailed in the documentation, the callback function returns a boolean which can be used to stop or continue the iteration:
Use a developer-defined function to invoke on each row in the search
results, up to 4000 results at a time. The callback function must use
the following signature: boolean callback(result.Result result); The
callback function takes a search.Result object as an input parameter
and returns a boolean which can be used to stop the iteration with a
value of false, or continue the iteration with a value of true.
...
mySearch.run().each(function(result) {
var entity = result.getValue({
name: 'entity'
});
var subsidiary = result.getValue({
name: 'subsidiary'
});
return true;
});
...
ResultSet.each(callback)

Validate In-Line Edits in Netsuite

I need to validate inline editing in NetSuite.
I already have a Client Script in place that works great when editing the record normally.
I tried adding a User Event script that on the before save function that validates the record, but it appears this is ignored with inline editing.
Has anybody ran into this before?
Any insight you can provide would be helpful. Thanks!
Edits:
The relevant code from the UE script:
function beforeSubmit(type){
if (type == "create" || type == "edit" || type == "xedit") {
var status = nlapiGetContext().getSetting("SCRIPT", "...");
var amount = Number(nlapiGetContext().getSetting("SCRIPT", "..."));
var nr = nlapiGetNewRecord();
var entitystatus = nr.getFieldValue("entitystatus");
var projectedtotal = Number(nr.getFieldValue("projectedtotal"));
if (entitystatus == status && projectedtotal >= amount) {
var statusText = nr.getFieldText("entitystatus");
var message = "ERROR...";
throw nlapiCreateError("...", message, true);
}
}
}
This applies to the opportunity record.
The field being validated is Projected Total with id projectedtotal.
My mistake, I misunderstood how xedit handled nlapiGetNewRecord(). Calling nlapiGetNewRecord when in xedit only returns the edited fields, not the entire record. Thus, the if statement was never true in xedit mode, because either the amount or the status would be null (it was very unlikely the user would edit both at the same time, and validation relies on both these fields' values).
I edited the code to lookup the field value if it is not present in the new record. Now everything works as expected!
Thanks everyone for the help!
For reference, the corrected code is below.
function beforeSubmit(type){
if (type == "create" || type == "edit" || type == "xedit") {
var status = nlapiGetContext().getSetting("SCRIPT", "...");
var amount = Number(nlapiGetContext().getSetting("SCRIPT", "..."));
var nr = nlapiGetNewRecord();
//Attempt to get values normally
var entitystatus = nr.getFieldValue("entitystatus");
var projectedtotal = Number(nr.getFieldValue("projectedtotal"));
var id = nr.getId();
//If values were null, it's likely they were not edited and
//thus not present in nr. Look them up.
if(!entitystatus){
entitystatus = nlapiLookupField("opportunity", id, "entitystatus");
}
if(!projectedtotal){
projectedtotal = Number(nlapiLookupField("opportunity", id, "projectedtotal"));
}
if (entitystatus == status && projectedtotal >= amount) {
var message = "ERROR...";
throw nlapiCreateError("101", message, true);
}
}
}
In your user event are you checking the value of the type parameter. For inline editing, the value of the type is 'xedit'.

alfresco search category case sensitive

I'm very new on Alfresco.
In a web script i have implemented category search.
var result = search.query("TYPE:\"cm:category\" AND #cm\\:name:CAt*").
but unfortnatly this search on category seems to be case sensitive. the results of search.query("TYPE:\"cm:category\" AND #cm\\:name:CAt*") and search.query("TYPE:\"cm:category\" AND #cm\\:name:cat*") are different.
How can i make search case insensitive?
I guess you should have done something with your lucene or solr configuration.As it seems work perfectly in my instance.Below is working image in my instance.
Or may be you are doing something wrong while testing.As you are executing this in your code may be some problem might be there.
Check your result in node browser.
bellow my webscript (well formatted version)
listData.get.js :
var term = args["term"];
var typeData = args["typeData"];
var searchResult ;
if( "1" == typeData )
{
searchResult = search.query({query: "TYPE:\"sc:site\"" });
}
else if( "2" == typeData )
{
searchResult = search.query({query: "TYPE:\"sc:fonction\"" });
}
else
{
var query = "TYPE:\"cm:category\" AND #cm\\:name:\""+term +"*\"" ;
searchResult = search.query({query: query });
}
And here is the descriptor file
listData.get.desc.xml :
<webscript>
<shortname>Une description du webscript</shortname>
<description> </description>
<url>/listData</url>
<authentication>user</authentication>
</webscript>
So i call webscript with http://localhost:9090/share/proxy/alfresco/listData?term=D

How to tell if a record exists in Mongo collection (C#)

Given a collection of items { url: 'http://blah' }. How can I tell if a record exists where the url is "http://stackoverflow.com"?
P.s. I am communicating with the c# driver
For any of the previous suggestions to be efficient you should be sure that there is an index on the url element. Otherwise a full collection scan will be required.
If you only expect the answer to be 0 or 1, count is probably the most efficient approach. If you think the count will be very large and all you really care about is whether there is one or more, FindOne is the most efficient approach.
It probably doesn't matter that FindOne returns the whole document unless the document is actually rather large. In that case you could tell the server to only return one field (the _id seems the most likely candidate):
var query = Query.EQ("url", "http://stackoverflow.com");
var fields = Fields.Include("_id");
var res = collection.Find(query).SetFields(fields).SetLimit(1).FirstOrDefault();
if (res == null) {
// no match found
}
you simply need check count of items returned by the query:
int count = collection.FindAs<Item>(Query.EQ("url", "http://stackoverflow.com")).Count();
if(count > 0)
{
//do some stuff
}
IMongoQuery query = Query.EQ("url", "http://stackoverflow.com");
var res = collection.FindOne(query);
if(res == null)//don't exist
{
}
Existence of Key in MongoDB can check by using Exists and second parameter as true or false
var filter = builder.Exists("style", false);
var RetrievedData = collection.Find(filter).ToList()
Refference Link

Resources