I have a two level JSON
{"Policy": {
"Channel": "online",
"Credit Score": "20000",
"Car": [{
"Age": "28",
"AnnualMiles": "15000",
"CarAge": "3",
"Young Driver": "1"
}
]
}}
i am trying to change the json structure and only retrieve the root policy object from the JSON
let data = JSON.parse(json);
console.log(data)
policy=data.Policy
console.log(policy)
The output that i am getting is the entire JSON basically, the result that i want is just the root level values :
{
"Channel": "online",
"Credit Score": "20000"
}
How do i only retrieve the root level in nodejs?
var json = {"Policy": {
"Channel": "online",
"Credit Score": "20000",
"Car": [{
"Age": "28",
"AnnualMiles": "15000",
"CarAge": "3",
"Young Driver": "1"
}
]
}}
//Filter function for objects
Object.filter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj[key]) )
.reduce( (res, key) => (res[key] = obj[key], res), {} );
//Exclude objects
let result = Object.filter(json.Policy, x => typeof x != "object")
console.log(result)
Output:
{
Channel: "online",
Credit Score: "20000"
}
Related
I want to filter out data based on search criteria in mongoDb.
Here is the query:
exports.getParkingListByCriteria = async (req, res) => {
const cityQuery = req.body.city;
const stateQuery = req.body.state;
const countryQuery = req.body.country;
const zipQuery = req.body.zipCode;
try {
const filter = await Parking.find({
$and: [
{
"location.city": { $regex: new RegExp(cityQuery, ($options = "i")) },
"location.state": { $regex: new RegExp(stateQuery, ($options = "i"))},
"location.country": { $regex: new RegExp(countryQuery, ($options = "i"))},
"location.zipCode": zipQuery,
},
],
});
res.status(200).send(filter);
} catch (error) {
return res.status(500).json({ error: error.message });
}
};
City, state and country are stored as a String and zipCode is stored as a Number in mongoose model.
city, state and country filter was just working fine. It was giving me an intended results but then I added a zipCode query and now city, state and countries filter is also giving an empty array.
request I am sending from postman:
{
"city": "edmund",
"state": "lousinia",
"country":"australia",
"zipCode": 49755
}
All are stored in a one collection like shown below:
{"_id": {"$oid": "62cc46e920782c4be0673d50"},
"merchantId": {"$oid": 62c950ebc96c2b690028be8b"},
"contactInfo": {"name": "Ronda Green", "phoneNumber": 9104933588},
"about": "Laborum non minim ad",
"location":
{"address": "349 scott avenue",
"city": "edmund",
"state": "louisiana",
"zipCode": 49755,
"country": "australia"},
"price": 18,
"parkingType": "parkingLot",
"parkingInfo": [{"parkingName": "College Place","_id":"$oid":"62cc46e920782c4be0673d51"},"default": []}],
"totalSpots": [168],
"parkingSpotType": ["Motorbike","Large"],
"coordinates":
{"lng": 1.522645,
"lat": 125.939061},
"status": "active",
"isFeePaid": false,
"availability": [],
"specialEvents": [],
"__v": 0}
Before the introduction of zipQuery to the code every individual request was working perfectly fine (Like if I pass a query { "city": "edmund" } it would give me above result) but after the zipQuery it just got messy.
The result of console.log(zipQuery) is 49755
I want to scan dynamodb using filter on product_id showing in below json of table.
Can anybody explain how to do scanning using filter of product_id.
Wants to scan dynamodb table data using documentclient.
Wants to find all fields which has product_id: something
{
"mandi_id": 1,
"product": [
{
"updated_price": 24,
"product_id": 2,
"last_price": 23
},
{
"updated_price": 24,
"product_id": 5,
"last_price": 23
}
],
"status": "active",
"createdAt": "2022-04-21T08:23:41.774Z",
"mandiCloseTime": "4pm",
"mandi_description": "anaj mandi",
"mandi_name": "gaziabad anaj mandi",
"state": "uttar pradesh",
"city": "gaziabad",
"main_image_s3": "",
"mandi_latlong": {
"lng": 77.48325609999999,
"lat": 28.680346
},
"mandiOpenTime": "10am",
"updatedAt": "2022-04-21T08:23:41.774Z",
"address_name": "gavindpuram",
"landmark_name": "mandi",
"village": "gaziabad",
"postal": "201013"
}
I have tried the following set of code but it is returning empty array list
var params = {
TableName: "dev-agrowave-mandi-management",
// Select: "ALL_ATTRIBUTES"
FilterExpression: "contains(#product,:product)",
ExpressionAttributeNames: {
"#product": "product",
},
ExpressionAttributeValues: { ":product": {"product_id":parseInt(id)}
}
};
let lastEvaluatedKey = 'dummy'; // string must not be empty
const itemsAll = [];
while (lastEvaluatedKey) {
const data = await docClient.scan(params).promise();
itemsAll.push(...data.Items);
lastEvaluatedKey = data.LastEvaluatedKey;
if (lastEvaluatedKey) {
params['ExclusiveStartKey'] = lastEvaluatedKey;
}
}
return {msg:itemsAll,params:params};
I am writing REST API in NodeJS with MongoDB. Structure of the database is:
[
{
"_id": "12345",
"name": "Meal name",
"category": "dessert",
"area": "british",
"imageUrl": "https.image.jpg",
"instructions": "some instructions...",
"ingredients": [
{
"name": "salt",
"measure": "1g"
},
{
"name": "chicken",
"measure": "1"
},
{
"name": "butter",
"measure": "90g"
}, ...
]
}, ...
]
I can write a route to get data which meet one condition,
i.e.:
//getting all, when category = :category
router.get('/meals/category=:category', async (req, res) => {
try {
const meals = await Meal.find({category: req.params.category})
res.json(meals)
} catch (err) {
res.status(500).json({ message: err.message })
}
})
Here, route
'meals/category=vegetarian'
get all data with category = vegetarian.
However, I want to have route, which will filter all data by parameters: category, area, ingredients.
For example:
meals/ingredients=salt,pepper&category=dessert&area=american
should return all data, which contains salt and pepper in array, and category = dessert.
another example:
meals/area=american&category=dessert
should return all data, where area=american and category=dessert
How can I write the router.get() method to achieve that?
When I accessing "dept_name", the JSON returns 'undefined'.
How can I return correct output?
JSON object (content) from an API
"departments": [
{
"dept_no": "d005",
"dept_name": "Development",
"from_date": "1994-07-03",
"to_date": "9999-01-01",
"dept_manager": [
{
"emp_no": 110511,
"first_name": "DeForest",
"last_name": "Hagimont",
"email": "110511#cloud-spartan.com",
"from_date": "1985-01-01",
"to_date": "1992-04-25"
},
{
"emp_no": 110567,
"first_name": "Leon",
"last_name": "DasSarma",
"email": "110567#cloud-spartan.com",
"from_date": "1992-04-25",
"to_date": "9999-01-01"
}
]
}
],
when I accessing data['departments'].dept_no returns 'undefined'
var content_depart = content['departments'];
console.log(content_depart);
var department = content_depart.dept_name;
console.log(department);
console.log(content_depart)
[ { dept_no: 'd005',
dept_name: 'Development',
from_date: '1994-07-03',
to_date: '9999-01-01',
dept_manager: [ [Object], [Object] ] } ]
console.log(department)
undefined
data['departments'] is an array.
let data =
{ // v--------- array !
"departments": [
{ // ...
You can't access its members directly, but have to specify the index first. In example :
let data = {"departments":[{"dept_no":"d005","dept_name":"Development","from_date":"1994-07-03","to_date":"9999-01-01","dept_manager":[{"emp_no":110511,"first_name":"DeForest","last_name":"Hagimont","email":"110511#cloud-spartan.com","from_date":"1985-01-01","to_date":"1992-04-25"},{"emp_no":110567,"first_name":"Leon","last_name":"DasSarma","email":"110567#cloud-spartan.com","from_date":"1992-04-25","to_date":"9999-01-01"}]}]};
console.log(data.departments[0].dept_no);
Add index before accessing data
var department = content_depart[0].dept_name;
console.log(department);
content_depart is array not an object
so go with content_depart[0].dept_name
i have a mongo collection like this
{"stores": [{"name": "foo",
"songs": [ {"id": "", "name": "", "artist": "", "category": "", "tags": []} ],
"songsSchedule": [
{
"song_id": "",
"date": ,
"user": "",
"help": ,
"partners": [{"user": ""}],
"likes":
}
]
}]}
and i want to get the songs name and artist from the songsSchedule song_id, i've tried this but it's not working
var query = { _id: fn.generateID(req.params.store_id), songsSchedule: { $exists: true } };
var select = { songsSchedule:1 };
var array = [];
client("stores", function(err, collection) {
if (err)
return res.json(fn.status("30"));
collection.findOne(query, select, function(err, store) {
if (err || !store)
return res.json(fn.status("31"));
for (var i in store.songsSchedule) {
var song = store.songsSchedule[i];
array.push(song.song_id);
}
collection.find({ _id: fn.generateID(req.params.store_id), "songs._id": { $in: array } }, function(err, songs) {
res.json(songs);
});
});
});
and i dont really know if it's the best way of doing it
I'm not entirely clear what you mean by "get the songs name and artist from the songsSchedule song_id" but it looks like that query will be messy.
If it were me, I'd consider splitting out songs and songSchedule into their own collections for easier querying.
from your document example, the "songs" field contains documents that do not contain an "_id" field.
"songs": [ {"name": "", "artist": "", "category": "", "tags": []} ]
But, your find() query is querying on the "songs._id" field.
Also, I'm not too familiar with the json() method, but does it handle cursors?
Regards,
Kay