Mongoose - find documents that match one or more conditions - javascript

I have three documents that look like this
{
"name": "X1",
"location": {
"country": "Ireland",
"state": "Dublin",
},
},
{
"name": "X2",
"location": {
"country": "Ireland",
"state": "Dublin",
"address": ""
},
},
{
"name": "C3",
"location": {
"country": "United States of America",
"state": "California",
"address": "San Jose"
},
I am trying to implement a filtering functionality to show documents based on multiple locations.
so, the endpoint URL looks like this for example http://localhost:3000/api/companies/stacks?state[]=Dublin&country[]=United%20States%20of%20America
So, it should return the three documents that are shown above, yet it only returns this document
{
"name": "C3",
"location": {
"country": "United States of America",
"state": "California",
"address": "San Jose"
},
Here is the source code, I am using Mongoose mainly.
//Filtering by location
if ('country' in req.query) {
const countries = [...country]
conditions['location.country']={$in:countries}
}
if ('state' in req.query) {
const states = [...state]
conditions['location.states'] = { $in: states }
}
const doc = await model
.find(conditions)
.sort({ p: -1, _id: 1 })
.lean()
.exec()
I understood that it returns the document that matches the country parameter, but I don't understand why it doesn't also fetch the other documents that has Dublin in states?
Edit: I also tried to use $or operator like that
find({
$or:[
{'location.country':'United States of America'},
{'location.states':'Dublin'}
]
})
Yet it also, returned the document that matches the country only. I thought about using aggregates but I am not sure if it is going to help me in my case?
Thanks in advance.

Related

How can i access data from a array of objects in json with reactjs

i have an array of objects in json and i want to pull only specific data from it, how can i do that?
heres my files:
import Stocks from "./stocks.json";
export default function Profile() {
return (
<>
<h1>{Stocks.symbol}</h1>
<h1>{Stocks.lastsale}</h1>
</>
);
}
and stocks.json
{
"symbol": "AAMC",
"name": "Altisource Asset Management Corp Com",
"lastsale": "$36.38",
"netchange": "0.88",
"pctchange": "2.479%",
"volume": "11317",
"marketCap": "64654718.00",
"country": "United States",
"ipoyear": "",
"industry": "Investment Managers",
"sector": "Finance",
"url": "/market-activity/stocks/aamc"
}
https://codesandbox.io/s/distracted-leftpad-ve6ch0?file=/App.js
this way above it works perfectly, the problem is that i want to have multiple objects inside the json file, as follow:
[
{
"symbol": "AAMC",
"name": "Altisource Asset Management Corp Com",
"lastsale": "$36.38",
"netchange": "0.88",
"pctchange": "2.479%",
"volume": "11317",
"marketCap": "64654718.00",
"country": "United States",
"ipoyear": "",
"industry": "Investment Managers",
"sector": "Finance",
"url": "/market-activity/stocks/aamc"
},
{
"symbol": "AAU",
"name": "Almaden Minerals Ltd. Common Shares",
"lastsale": "$0.2167",
"netchange": "-0.0036",
"pctchange": "-1.634%",
"volume": "196889",
"marketCap": "29735879.00",
"country": "Canada",
"ipoyear": "2015",
"industry": "",
"sector": "",
"url": "/market-activity/stocks/aau"
}
]
my objective is to pull the data from a specific stock, like the "lastsale" for example
thanks in advance!
in kinda new to programming
i want to be able, to pull only the data from a specific stock, like using the AMMC symbol as a input to get the "lastsale" from it
You would need to find your desired stock using array search methods like, .find, .findIndex or just .filter.
In this specific case you can use:
const AAMCStock = Stocks.find(stock => stock.symbol === "AAMC")
const lastSale = AAAMStock.lastsale
You can find more information about this method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Find all cities in a country/state or finding the state/country given a city from JSON data

I have county/state/city data in JSON (shown below). I want to find all cities given a state/country and given a city, need to find the state and country.
List all cities in country: usa
List all cities in states: Alabama
List the state and country for city: Adamsville
{
"country": "usa",
"states": [
{
"name": "Alabama",
"state_code": "AL",
"cities": [
{
"name": "Abbeville",
"latitude": "31.57184000",
"longitude": "-85.25049000"
},
{
"name": "Adamsville",
"latitude": "33.60094000",
"longitude": "-86.95611000"
}
]
},
{
"name": "Alaska",
"state_code": "AK",
"cities": [
{
"name": "Akutan",
"latitude": "54.13350000",
"longitude": "-165.77686000"
},
{
"name": "Aleutians East Borough",
"latitude": "54.85000000",
"longitude": "-163.41667000"
}
]
}
]
}
Here are built-in Array functions that will help you get what you want.
Array.prototype.find() - returns the value of the first element in an array that satisfies the provided test.
To find the state object in your JSON data, you can do this:
const findState = (name) => data.states.find(state => state.name === name);
let alaska = findState('Alaska');
// { "name"; "Alaska", "state_code": "AK", "cities": [...] }
To find the cities in a state, use the above findState to get the state object, then Array.prototype.map() will form an array of just the city names:
let alaska = findState('Alaska');
let citiesInAlaska = alaska.cities.map(city => city.name);
// [ "Akutan", "Aleutians East Borough" ]

Setting Relationships in MongoDB with ObjectID only

In MongoDB the relationships can be are set by using the _id of the parent in the child object example In the two objects written below the relationship is set between the two by the owner attribute.
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"name": "Tom Hanks",
"contact": "987654321",
"dob": "01-01-1991"
}
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"owner": ObjectId("52ffc33cd85242f436000001"),
"address": [
{
"building": "22 A, Indiana Apt",
"pincode": 123456,
"city": "Los Angeles",
"state": "California"
},
{
"building": "170 A, Acropolis Apt",
"pincode": 456789,
"city": "Chicago",
"state": "Illinois"
}
]
}
My concerns is to take a decision between two collection based on _id attribute, if I use the _id attribute in the child collection should be it of type ObjectID (as shown in the example above) or should the child object use the _id vale from the parent as a string type (eg "owner": "52ffc33cd85242f436000001"),
what should be the best practice with some pons and cons.

How to Partially Update a DynamoDB Table?

We're having a lot of trouble doing a partial update in DynamoDB.
Trying to use best practices in NoSQL by using aggregates instead of entities so our data looks a bit like this:
[
{
"userLogin": {
"ipAddress": "123.222.121.1234",
"lastLogin": "2017-10-16T17:38:59.818Z",
"userAgent": "bob",
"geoLocation": "lat-121 long-312"
},
"addresses": {
"billingAddress": {
"streetName": "york street",
"province": "ontario",
"city": "toronto",
"streetNumber": "18",
"postalCode": "m5a2v7"
},
"businessAddress": {
"streetName": "york street",
"province": "ontario",
"city": "toronto",
"streetNumber": "18",
"postalCode": "m5a2v7"
},
"mailingAddress": {
"streetName": "york street",
"province": "ontario",
"city": "toronto",
"streetNumber": "18",
"postalCode": "m5a2v7"
},
},
"paymentTransaction": {
"orderId": 5,
"amount": 75,
"transactionTimestamp": "2017-10-16T17:38:59.818Z"
},
"userId": "00uc4sxyi7gfQoFum0h7",
"phoneNumbers": {
"workNumber": "647-123-1234",
"homeNumber": "647-321-4321"
},
"userProfile": {
"role": "admin",
"verifiedTimeStamp": "2017-10-16T17:38:59.818Z",
"termsConditionTimeStamp": "2017-10-16T17:38:59.818Z",
"verified": "TRUE",
"createdTimeStamp": "2017-10-16T17:38:59.818Z",
"termsConditionVersion": "1.0",
"email": "kyle.truong#test.io"
}
}
]
All we want to do is make a request with a body like this:
PUT /api/user-profiles/00uc4sxyi7gfQoFum0h7
body: {
"userLogin": { "lastLogin": "2017-12-16T17:38:59.818Z" }
}
and have it update the one attribute in the User table.
The updateItem API seems to require defining the attributes you want to update before updating them, but we want it be more flexible and dynamic based on the body of the request.
This thread seems to say it's not possible:
How to update multiple items in a DynamoDB table at once
If so, what's the best way to go about updating just a partial attribute object within an item in DynamoDB?
In dynamoDB if your userLogin is a map type then you can update the value of lastLoginkey. In Java below code may help. Here column name would be userLogin and newKey would be lastLogin. Full code snippet can be found here
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(primaryKey,primaryKeyValue).withReturnValues(ReturnValue.ALL_NEW).
withUpdateExpression("set #columnName." + newKey + " = :columnValue").
withNameMap(new NameMap().with("#columnName", updateColumn)).
withValueMap(new ValueMap().with(":columnValue", newValue)).withConditionExpression("attribute_exists("+ updateColumn +")");
table.updateItem(updateItemSpec);

Accessing json data from wunderground API?

I have this async function below that taps into a weather API and I would just like to retrieve two pieces of info from the API: Temperature in F & C. I removed the API_Key but it's free to get one on the site if necessary.
I can confirm I am receiving the json object due to my console.log(response) statement, but Im not sure how to access these data points in such heavily embedded json notation.
I guess my question is if I wanted to access say 'full' for full city name I thought I'd do something like response.observation_location.full but that doesn't work...
Help?
async loadWeather() {
// let zip = this.args.zip || 97239;
let response = await fetch(`http://api.wunderground.com/api/API_KEY/conditions/q/CA/San_Francisco.json`);
console.log(response);
this.weather = await response.json();
// setTimeout( () => { this.loadWeather(); }, 2000);
}
Here is a partial output of the response json:
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "San Francisco, CA",
"city": "San Francisco",
"state": "CA",
"state_name": "California",
"country": "US",
"country_iso3166": "US",
"zip": "94102",
"magic": "1",
"wmo": "99999",
"latitude": "37.77999878",
"longitude": "-122.41999817",
"elevation": "60.0"
},
"observation_location": {
"full": "SOMA, San Francisco, California",
"city": "SOMA, San Francisco",
"state": "California",
"country": "US",
"country_iso3166": "US",
"latitude": "37.778488",
"longitude": "-122.408005",
"elevation": "23 ft"
},
I have tried doing console.log(response["current_observation"]) just to access a nested data value but that doesnt seem to work as it returns undefined.
Ok I solved my own issue, but for the record:
response needed to be converted to json via resonse.json()
and then I can access properties as expected
this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);

Categories

Resources