MongoDB find method with variables - javascript

Trying to search through my mongoDB database using variable names not by specifying the exact search. Is it possible to do this? No matter how i try to format the variable I can't get a successful search. I'm trying to do something like the bottom line below
let url3 = 'http://cs544.io/11jgry2';
const ret = await dbTable.find({"shortUrl" : "http://cs544.io/11jgry2"}); //Works
const ret = await dbTable.find({"shortUrl" : url3}); //Doesn't work

Use $eq it Specifies equality condition. The $eq operator matches documents where the value of a field equals the specified value.
Check this this for further explanation and examples

Theoretically, it should work,
But I suggest having a look into using $eq instead.
Here is an example
const ret = await dbTable.find( { shortUrl: { $eq: url3 } } );

Related

how to Sequelize "where" accessing table and column

I am attempting to port an application that had used sequelize 3.30.4 and I'm updating to 6.13, I'm assuming some things have changed because I can't use string literals in a where clause, or so the debugger tells me.
That said, I've done some googling and have found some basic examples that make sense sure but I'm not entirely sure how to convert this string to a format acceptable for findAndCountAll to be happy.
I've attempted something like this, thinking it might at least point me in the right direction however it does not.
let attributes = ['id', 'name', 'locationId'];
let where = undefined;
let order = [['name', 'ASC']];
where = {
classroom: {
locationId: request.query.locationId
}
}
this is the line that did at one time work but no longer works.
where = `"classroom"."locationId" = ${request.query.locationId}`;
const classrooms = await model.classroom.findAndCountAll(_.assign({},
requestHelper.computePaginationObject(request.query.limit, request.query.page), {
attributes,
where: where ? [where] : undefined,
order
}));
how would I go about porting this into the proper format?
Try something like this:
let where = {}
if (<some condition>) {
where = {
locationId: request.query.locationId
}
}
const classrooms = await model.classroom.findAndCountAll(_.assign({},
requestHelper.computePaginationObject(request.query.limit, request.query.page), {
attributes,
where: where,
order
}));
You can also try that even if the first comment of ANATOLY works wonders :
const where = <some condition> ? {locationId: request.query.locationId} :{};
const classrooms = await model.classroom.findAndCountAll(_.assign({},
requestHelper.computePaginationObject(request.query.limit, request.query.page), {
attributes,
where,
order
}));

push only unique values into array

not able to check the unique values log showing all values getting
added to the array
.
var moveToReady = [];
var topLinesRecords = new GlideRecord('x_snc_ms_dynamics_d365_queue');
topLinesRecords.addEncodedQuery('root_element_sys_id=03133e1a1bfe6410f8ca0e16624bcba7');
topLinesRecords.orderByDesc('sys_created_on');
topLinesRecords.query();
while(topLinesRecords.next()){
gs.info(' first record : ' + topLinesRecords.number);
if(moveToReady.indexOf(topLinesRecords.getValue('object_sys_id')) == -1){
moveToReady.push(topLinesRecords.getValue('object_sys_id'));
}
gs.info('array. : ' + moveToReady);
updateRecordtoFail(topLinesRecords);
}
You can use the Set structure from ES6 to make your code faster and more readable:
// Create Set
this.items = new Set();
add(item) {
this.items.add(item);
// Set to array
console.log([...this.items]);
}
you may use array.includes
if (!moveToReady.includes(topLinesRecords.getValue('object_sys_id'))){
moveToReady.push(topLinesRecords.getValue('object_sys_id'));
}
So, some tips to get unique values on ServiceNow:
-GlideRecord has a "getUniqueValue" method
(URL: https://docs.servicenow.com/bundle/paris-platform-administration/page/administer/table-administration/concept/c_UniqueRecordIdentifier.html)
-You can search on your Script Includes a OOB method/function to get only unique values. Search for "utils". Every instance has this, maybe "ArrayUtils".
Hope this information helped!

Split out props.location.search value

I'm trying to split out the values from props.location.search in React/Redux. I've successfully obtained the mixOne split however I can't seem to return the value of quantity. Here's my code:
const mixOne = props.location.search
? String(props.location.search.split("mixOne=")[1])
: "None";
const quantity = props.location.search
? Number(props.location.search.split("=")[1])
: 1;
And here's the URL that gets generated:
const addToCartHandler = () => {
props.history.push(
`/Cart/${productId}?quantity=${quantity}?mixOne=${mixOne}`
);
};
As you can see quantity returns null, when I need the value selected
props.location.search.split("=") on "?quantity=1?mixOne=Grape" would return [ '?quantity', '1?mixOne', 'Grape' ] since the next = is not until after mixOne.
There's a few different fixes here.
Your query string is invalid– a ? denotes the start of the query string. Separate parameters should be split up using & ampersand characters. It should look like this: ?quantity=1&mixOne=Grape
If you follow the standard here, you can then split it two ways: by = and then by & to get the different parameters. However, there is an easier way.
Using the new-ish URLSearchParams API, you can parse your parameters in a predictable way:
// Use the constructor with your `props.location.search`
const queryParams = new URLSearchParams(props.location.search);
// Use the getters to grab a specific value
const quantity = queryParams.get("quantity");
// Ensure it's a number for safety
const quantityNum = Number(quantity);
// ... the rest of your code here
The query is wrong. You're using double question marks. The second ? should be replaced with &.
?quantity=1&mixOne=Grape

Postman get variable used in array find doesn't work

Using the newest version of Postman.
I have a predefined variable "useridToken" which is a number: 123456
var useridToken = pm.environment.get("useridToken");
//console.log(useridToken);
var jsonData = pm.response.json();
const user = jsonData.find(u => u.user_metadata.employeeId === useridToken);
const userid = user ? user.user_id : 'not found';
pm.environment.set("user_id", userid);
Whenever I run this code, it returns errors.
The console log output is the number as an integer: 123456
Whenever I run the following code:
var useridToken = 123456
var jsonData = pm.response.json();
const user = jsonData.find(u => u.user_metadata.employeeId === useridToken);
const userid = user ? user.user_id : 'not found';
pm.environment.set("user_id", userid);
It works like a charm, but I don't want the hardcoded useridToken in my code, I would like to get it from my environment variables. I don't quite understand why the first part isn't working? What am I overseeing?
This is happening because in your .find method you're using === comparison, and when you fetch from environment you always get it as a 'string' and not a 'number' (Postman always gives the value of the environment variable in the string format)
So when you use a === comparison in JS, it also checks the type of the data, here
string === number will actually be false and that's why your find doesn't work.
So, you need to update your code to actually parse the integer that you got from the environment.
This should fix your issue:
var useridToken = parseInt(pm.environment.get("useridToken"));
SOLUTION:
Since you are using === operator, it checks for the type of the variables too. The type for both operands might be different on certain scenarios. So, use the following to avoid the issue.
const user = jsonData.find(u => +u.user_metadata.employeeId === +useridToken); // converts to number then checks
or
const user = jsonData.find(u => u.user_metadata.employeeId.toString() === useridToken.toString()); // converts to string then checks
or
const user = jsonData.find(u => u.user_metadata.employeeId == useridToken); // checks without the operands type. (not recommended)

firebase -> date order reverse

I am currently making an app using Firebase.
It is one of those bulletin boards that can be seen anywhere on the web.
But there was one problem.
This is a matter of date sorting.
I want to look at the recent date first, but I always see only the data I created first.
postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
console.log(data.val().name + data.val().createData);
})
result - >hello1496941142093
My firebase tree
My code is the same as above.
How can I check my recent posts first?
How Do I order reverse of firebase database?
The Firebase Database will always return results in ascending order. There is no way to reverse them.
There are two common workaround for this:
Let the database do the filtering, but then reverse the results client-side.
Add an inverted value to the database, and use that for querying.
These options have been covered quite a few times before. So instead of repeating, I'll give a list of previous answers:
Display posts in descending posted order
Sort firebase data in descending order using negative timestamp
firebase sort reverse order
Is it possible to reverse a Firebase list?
many more from this list: https://www.google.com/search?q=site:stackoverflow.com+firebase+reverse%20sort%20javascript
You can simply make a function to reverse the object and then traversing it.
function reverseObject(object) {
var newObject = {};
var keys = [];
for (var key in object) {
keys.push(key);
}
for (var i = keys.length - 1; i >= 0; i--) {
var value = object[keys[i]];
newObject[keys[i]]= value;
}
return newObject;
}
This is how I solved it:
First I made a query in my service where I filter by date in milliseconds:
getImages (): Observable<Image[]> {
this.imageCollection = this.asf.collection<Image>('/images', ref => ref.orderBy('time').startAt(1528445969388).endAt(9999999999999));
this.images = this.imageCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Image;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
return this.images;
}
Then to get the newest date first I added this to my component where I call the method from my service:
let date = new Date;
let time = 9999999999999 - date.getTime();
console.log(time);
I pass the time let as the date. Since a newer date will be a bigger number to deduct from the 9999999999999, the newest date will turn up first in my query inside my service.
Hope this solved it for you
If you want to display it in the front end, I suggest that after you retrieve the data, use the reverse() function of JavaScript.
Example:
let result = postRef
.orderByChild("createData")
.startAt(reverseDate)
.limitToFirst(1)
.on("child_added", data => {
console.log(data.val().name + data.val().createData);
});
result.reverse();
Ive ended changing how I create my list on the frontend part.
was
posts.add(post);
changed to
posts.insert(0, post);
You could use a method where you save the same or alternate child with a negative value and then parse it.
postRef.orderByChild('createData').orderByChild('createData').on('child_added',(data)=>{
console.log(data.val().name + data.val().createData);})
Far more easier is just use Swift's reversed():
https://developer.apple.com/documentation/swift/array/1690025-reversed
https://developer.apple.com/documentation/swift/reversedcollection
let decodedIds = try DTDecoder().decode([String].self, from: value)
// we reverse it, because we want most recent orders at the top
let reversedDecodedIds = decodedIds.reversed().map {$0}
orderBy("timestamp", "desc")
I think you can give a second argument name "desc".
It worked for me

Categories