How to check if data received from mongo database is empty? - javascript

So, I'm trying to check if the data from my .find() is empty. I can check if it's null`, but I realize that when the .find() finds nothing, it returns an empty list. When I have an if statement saying
if (docs = []) {
// code here
} else {
// code here
}
It doesn't do the code and instead does the code if the documents got from the database. How can I make it check if it's an empty list?

Check for length being 0 like if(docs.length === 0)

Related

Why JavaScript null check doesn't working?

function readProperty(property)
{
console.log(localStorage[property]) //Alerts “null”
if(localStorage[property] == null)
{
console.log('Null chek')
return false;
}
return localStorage[property];
}
log outputs "null", but 'if()' doesn't work. I try with ===, its not work too. Help please.
UPD: Thanks everyone this change helped me if(localStorage[property] == 'null')
The keys and the values stored with localStorage are always in the
UTF-16 string format, which uses two bytes per character. As with
objects, integer keys are automatically converted to strings.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Try:
localStorage[property] === 'null'
Although: console.log(localStorage[property]) may report null, the actual value is undefined.
So, in your if statement, if you test against undefined, you'll get a match.
Better yet though, just test for the existence or non existence of a value with:
if(localStorage[property])... // Tests for any "truthy" value
or
if(!localStorage[property])... // Tests for any "falsey" value
Well, I don't know if you're trying to use the global localStorage or if it's a defined variable in your code.
If you're using the localStorage API, you should check if a key exists like this...
if (!localStorage.getItem("my-item")) {
console.log("item doesn't exist.");
}
The .getItem() method returns null when the key isn't defined so checking using ! or item !== null work.
.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.
you have to get item from localStorage using getItem() function like that
if(!localStorage.getItem(property) || localStorage.getItem(property)===null){
// there is no item in localStorage with the property name
}

how to stop mongoose/javascript adding null values to arrays?

I have a mongoose schema which has a field of comments: [String].
When I try to update the schema, I am checking if the value is null or empty by adding the following code into my controller,
if (req.body.comments !== null || req.body.comments !== '') {
container.comments.push(req.body.comments)
}
container.save() ...
However when I run this code (using postman for testing) and do not provide a value for the comment field, it updates in the database as null in the array.
comments: [String] is in the main schema definition and not part of a suc-document or anything like that.
Would anybody know a way round this issue or why this happens?
Make sure that comments is not undefined, you can handle all cases this way:
if (req.body.comments && req.body.comments !== '') {
container.comments.push(req.body.comments)
}
That way empty strings, null and undefined values are not added, assuming req.body.comments always comes in as a string.
You need to set container.comments as an empty array before you reach your condition statement
container.comments = container.comments || []
if (req.body.comments && req.body.comments !== '') {
container.comments.push(req.body.comments)
}
this way the data saved on your database will always be an array, regardless of your sending comments on your request or not.
also its worth mentioning that saving an empty array on monggose will result to undefined unless you override it.
edited the example to take consideration if the array is not empty

Get object from array based on property using Lodash _.find

I have an array of objects, say memberToChange.checkboxes: ICheckbox[] like this:
Now, I have a variable, say internalNumber: string which has the value "3419". I want to get the object from the array of objects where the internalNumber matches the label property. Ultimately, I want to set the value attribute of that object to true.
My code is:
let checkboxes = _.find(scope.selectedMembers, (member: IMember) => member.member.uuid === memberId).checkboxes; //gives me array of checkboxes.
let checkboxToChange = _.find(memberToChange.checkboxes, function(checkbox: ICheckbox){
return (checkbox.label === internalNumber);
}); //gives me null, moreover, even a console.log inside the second find doesn't print. I'm thinking the two consecutive _.find statements are messing something up, not sure what.
For reference, this is my ICheckbox interface:
export interface ICheckbox {
label: string;
sublabel?: string;
value: boolean;
numberUuid: string;
}
I would expect that for internalNumber 3419, it should return me the second object from the array. But it returns undefined. I'm not sure what's going on here.
If there is a better way to find and set the value to true in one go only, I'd be happy to know that as well.
Any help is appreciated. Thank you.
Update:
After someone suggested using filter method of javascript, I tried this: (my scope is assigned to this)
scope.selectedMembers.filter(function(member) {
if (member.member.uuid === memberId) {
scope.memberCheckboxes = [];
console.log('found member'); //prints
scope.memberCheckboxes = member.checkboxes;
console.log(scope.memberCheckboxes); // print correctly, with checkboxes of the member
scope.memberCheckboxes.filter(function(checkbox) {
console.log('inside checkbox function'); //control doesnt even come here
if (checkbox.label === intNum) {
console.log('found checkbox'); // control doesnt come here
}
});
}
});
Here, I don't understand why the first console.log inside scope.memberCheckboxes.filter doesn't print? Am I missing something obvious here?
By some reason your memberToChange.checkboxes (or member.checkboxes in your updated question) have no elements.
It is the only explanation why it does not work since your code is otherwise correct. The fact that console.log('inside checkbox function') does not print confirms that.

Checking for a value inside jQuery cookie object

I'm using Jquery.cookies plugin but I can't seem to find the information i'm looking for.
I have the cookie object which contains keys and values for cookies that are set on the page.
Want I need to do is loop through the object and check to see if a value exists inside the object and if it does log it to the console.
$.cookie().each(function() {
if (index == ratingsID) {
console.log(index)
}
});
With the above code I get an error that says undefined is not a function.
Can anyone point me in the right direction?
Thanks
if($.cookie("MyCookie") != null){
cookie = JSON.parse($.cookie("MyCookie"));
cookie.forEach(function(elem){
console.log(elem);
});
}
Try this

Checking for null objects in javascript

I have the following code snippet that defines the property values in my form.
function retrieve(){
setSelectedIndex(document.producerSetForm.GA1,"<%=ssnGA1%>");
setSelectedIndex(document.producerSetForm.GA2,"<%=ssnGA2%>");
setSelectedIndex(document.producerSetForm.GA3,"<%=ssnGA3%>");
setSelectedIndex(document.producerSetForm.GA4,"<%=ssnGA4%>");
setSelectedIndex(document.producerSetForm.GA5,"<%=ssnGA5%>");
}
where these ssnGA1,ssnGA2 etc may or may not be having a value. I need to check whether whether they have a value to do some more processing. I tried
var len=<%=ssnGA1.toString().length()%>;
if(len !=0)
but it works only if the value is present. else it giving javascript error. Please help. THANKS
You have to check if your string is not undefined/null first, on example:
if ( ssnGA1 && ssnGA1.toString().length ) {
// do something
}
Also, length is a property, not a function, see MDN for details.

Categories