mongodb api for fetch in data - javascript

I have below JSON:
{
"program_objective": "",
"program_type": "Post Graduate",
"creation_date": "2020-01-04T04:45:28.418Z",
"dstatus": "",
"_id": "5e101e26a96cc905745721b0",
"program_name": "Hardware",
"short_code": "Hdw",
"program_induc_date": "2020-01-28T18:30:00.000Z",
"program_cat": "Certificate",
"program_years": "0",
"program_months": "6",
"depart_id1": "Msc IT ",
"PEO": [
{
"_id": "5e1300d826c155310c6ae384",
"peo": "Hardware",
"weight": 212
},
{
"_id": "5e1300d826c155310c6ae383",
"peo": "Hardware",
"weight": 212
}
],
"Name": [],
"PO": [],
"__v": 0
}
I want the PEO value from above JSON but when I am trying to get "PEO":{}, it is returning null.
router.route('/getprogram/:id/PEO/').get((req, res, next) => {
addmissionForm.programSchema.findById(req.params.id, (error, data) => {
console.log(data.PEO)
if (error) {
return next(error)
} else {
res.json(data)
}
})
});

Related

NodeJS hendt/ebay-api / getOrders / Error - Insufficient permissions to fulfill the request

So I am using the hendt/ebay-api library but having no success with the getOrders call.
Here's the auth scopes I'm using when setting the ORIGINAL User access token...:
eBay.auth.oAuth2.setScope([
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
]);
Here's my code (ExpressJS backend controller method...):
exports.getOrders = async (req, res) => {
let _id = req.params.userId; // user's _id
let token = await refreshEbayToken(_id, eBay)
console.log(`token...`, token) // not an array! It's an object!
// set OAuth2 eBay credentials
eBay.auth.oAuth2.setCredentials(token.access_token);
try {
let result = await eBay.sell.fulfillment.getOrders({
filter: 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
limit: 5
})
console.log(`Got a result...`, result)
res.json(result)
} catch (e) {
console.log(`Got an error in getOrders...`, e)
res.status(400).json( { error: e } )
}
}
Here's the error I get:
{
"meta": {
"errors": [
{
"errorId": 1100,
"domain": "ACCESS",
"category": "REQUEST",
"message": "Access denied",
"longMessage": "Insufficient permissions to fulfill the request."
}
]
},
"name": "EBayAccessDenied"
}
Even freshly minted User access tokens through those scopes get this error.
According to the ebay docs on getOrders, these are the required auth scopes for this call:
https://api.ebay.com/oauth/api_scope/sell.fulfillment
https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly
Upon further investigation, I found I am certainly using those scopes in the response (below is a snippet of the scopes grabbed from the larger ebay error)...
...%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.fulfillment.readonly%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.fulfillment%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.analytics.readonly%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.finances%20...
As shown above, I am clearly using the sell.fulfillment and sell.fulfillment.readonly scopes so I do not understand what is the issue.
What do you think could be the issue?
So I am using the library but having no success with the getOrders call.
Here's the auth scopes I'm using when setting the ORIGINAL User access token
https://gist.github.com/mudassaralichouhan/d952b464b2907c7f833c87c05152eb76
I finally got it working.
Here is an example of what I receive now:
{
"sales": [
{
"orderId": "xxxxxxxxx",
"legacyOrderId": "xxxxxxxxx-xxxxxxxxx",
"creationDate": "2022-03-09T23:10:36.000Z",
"lastModifiedDate": "2022-03-18T15:51:04.000Z",
"orderFulfillmentStatus": "FULFILLED",
"orderPaymentStatus": "PAID",
"sellerId": "xxxx",
"buyer": {
"username": "xxxxx",
"taxAddress": {
"stateOrProvince": "xx",
"postalCode": "xxxxxxxx",
"countryCode": "xx"
}
},
"pricingSummary": {
"priceSubtotal": {
"value": "xxxxx",
"currency": "USD"
},
"deliveryCost": {
"value": "0.0",
"currency": "USD"
},
"total": {
"value": "xxxxx",
"currency": "USD"
}
},
"cancelStatus": {
"cancelState": "NONE_REQUESTED",
"cancelRequests": []
},
"paymentSummary": {
"totalDueSeller": {
"value": "xxxxx",
"currency": "USD"
},
"refunds": [],
"payments": [
{
"paymentMethod": "EBAY",
"paymentReferenceId": "xxxxxx",
"paymentDate": "2022-03-09T23:15:33.109Z",
"amount": {
"value": "xxxxxxxx",
"currency": "USD"
},
"paymentStatus": "PAID"
}
]
},
"fulfillmentStartInstructions": [
{
"fulfillmentInstructionsType": "SHIP_TO",
"minEstimatedDeliveryDate": "2022-03-14T07:00:00.000Z",
"maxEstimatedDeliveryDate": "2022-03-19T07:00:00.000Z",
"ebaySupportedFulfillment": false,
"shippingStep": {
"shipTo": {
"fullName": "xxxxxxxxxx",
"contactAddress": {
"addressLine1": "xxxxxxxxxxx",
"city": "xxxxxxxxxx",
"stateOrProvince": "xx",
"postalCode": "xxxxxxxxx",
"countryCode": "US"
},
"primaryPhone": {
"phoneNumber": "xxxxxxxxxxxxx"
},
"email": "xxxxxxxxxxxx#members.ebay.com"
},
"shippingServiceCode": "ShippingMethodStandard"
}
}
],
"fulfillmentHrefs": [
"https://api.ebay.com/sell/fulfillment/v1/order/xxxxxxxxxxx/shipping_fulfillment/xxxxxxxxxx"
],
"lineItems": [
{
"lineItemId": "xxxxxxxxxx",
"legacyItemId": "xxxxxxxxxx",
"legacyVariationId": "xxxxxxxxxx",
"sku": "xxxxxxxxxx",
"title": "xxxxxxxxxx",
"lineItemCost": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"quantity": 1,
"soldFormat": "FIXED_PRICE",
"listingMarketplaceId": "EBAY_US",
"purchaseMarketplaceId": "EBAY_US",
"lineItemFulfillmentStatus": "FULFILLED",
"total": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"deliveryCost": {
"shippingCost": {
"value": "0.0",
"currency": "USD"
}
},
"appliedPromotions": [],
"taxes": [],
"ebayCollectAndRemitTaxes": [
{
"taxType": "STATE_SALES_TAX",
"amount": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"collectionMethod": "NET"
}
],
"properties": {
"buyerProtection": true
},
"lineItemFulfillmentInstructions": {
"minEstimatedDeliveryDate": "2022-03-14T07:00:00.000Z",
"maxEstimatedDeliveryDate": "2022-03-19T07:00:00.000Z",
"shipByDate": "2022-03-14T06:59:59.000Z",
"guaranteedDelivery": false
},
"itemLocation": {
"location": "xxxxxxxxxx",
"countryCode": "US",
"postalCode": "xxxxxxxxxx"
}
}
],
"ebayCollectAndRemitTax": true,
"salesRecordReference": "xxxxxxxxxx",
"totalFeeBasisAmount": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"totalMarketplaceFee": {
"value": "xxxxxxxxxx",
"currency": "USD"
}
}
]
}
Here are my scopes:
eBay.auth.oAuth2.setScope([
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
]);
Here is the code getting it right ( express.js )...
exports.getOrders = async (req, res) => { // https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetOrders.html
let _id = req.params.userId; // user's _id
let a = {}
a._id = _id
a.userDoc = await User.findById( { _id: a._id } )
eBay.auth.oAuth2.setCredentials( a.userDoc.token[ 0 ] ) // set OAuth2 eBay credentials
try
{
a.result = await eBay.trading.getOrders({
filter: 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
limit: 5
})
console.log(`Got a result...`, a.result)
} catch ( e ) {
}
}
I send in the mongodb user _id as request params and use that to pull out their user token, which is passed into eBay.auth.oAuth2.setCredentials( a.userDoc.token[ 0 ] ) and allows the call to actually be made... eBay.trading.getOrders
I hope this helps someone out there. I remember being unable to make this call for months.

How To $pull From Deeply Nested Document (mongoose)

I need to delete a location object from the locations array. It is deeply nested. I followed mongoose documentation but my attempts didn't work:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
},
{
"locationName": "Loc3",
"count": 30,
"_id": "7cb0c1f51a91c384846d65f8b2ae"
}
]
},
{more lists}
Attempt:
router.post("/lists/deleteLoc", (req, res) => {
const {
listId,
list_id,
item_id,
location_id
} = req.body;
List.updateOne({
"lists.listId": listId,
"lists._id": list_id
}, {
$pull: {
"lists.$.items": {
locations: {
$elemMatch: {
_id: location_id
})
.then(() => res.json({
msg: "location removed"
}))
.catch((err) => res.status(400).json({
msg: "Error: " + err
}));
});
If the request location_id was "7cb0c1f51a91c384846d65f8b2ae" it should delete the last location from the array. The desired result:
lists = [{
"listName": "Test",
"_id": "8d55f0afe545a0178c320706",
"listId": "5fd9a3bef6c39b2f9c4df65b",
"date": "12/15/2020",
"dueDate": "2020-11-18",
"items": [
{
"itemNumber": 123,
"description": "item123",
"onHand": 60,
"_id": "13dd1f26ecd2baeb61b3b455",
"locations": [
{
"locationName": "loc1",
"count": 10,
"_id": "50a2c969465ba8010bd48977"
},
{
"locationName": "loc2",
"count": 20,
"_id": "51c2f1d25311dc8fabdbf604a59b"
}
]
},
{more lists}
I've tried basically all variations of this, but none have worked.
I'm also not sure if making a router.post or an axios.post request for deletion is correct. Should this be axios.delete and router.delete?
I've tried this in one of my similar DB and worked!
List.updateOne({ "listId": yourListId },
{
'$pull': {
'items.$[item].locations': { "_id": yourLocationId }
}
}, {
"arrayFilters": [
{
"item._id": yourItemId
}
]
}, function (err) {
if (err) {
res.json(err)
} else {
res.json({ message: "Updated" })
}
})
}
You've to put the values that're inside your DB from the object that you want to delete.
So if you want to delete the object with
"locationname" : "Loc3"
You should use
var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";
Try it out!

How can find in object at object of array in express

For each post I have this structure:
{
"_id": "5dfd3b918937d40b98afd3f8",
"user": "5deea38cfc84f42590e01942",
"title": "test",
"description": "description test",
"category":
{
"0": "1",
"1": "101"
},
"phone": "+1",
"country": "USA",
"city": "NY",
"options": {
"transaction_type": ""
},
"date": "2019-12-20T21:22:25.940Z",
}
In express I using bottom code for find posts by category id but not working what I should to do?
router.get("/category/:category", async (req, res) => {
try {
const posts = await Post.find({
category: { $all: req.params.category }
}).sort({ date: -1 });
if (!posts) {
return res.status(404).json({ msg: "Ads not found" });
}
const resultPosts = posts.slice(req.query.start, req.query.count);
res.json(resultPosts);
} catch (err) {
console.error(err.message);
if (err.kind === "ObjectId") {
return res.status(404).json({ msg: "Ads not found" });
}
res.status(500).send("Server Error!");
}
});

Iterating through an array of objects to filter specific data

I am trying to get specific data filtered on an API call. The objects are not iterable and I have tried a million different ways to get the specific data I need.
So...I need to filter out tip_money and return only that data instead of the full response.
Here is the call
router.get('/', auth, (req, res) => {
try {
apiInstance.listPayments(opts).then(function (payments) {
res.send(payments)
})
} catch (error) {
console.error(error)
}
});
and here is the response (partially):
{
"payments": [
{
"id": "rt6Q8LL3XrCLGltl3bBhazMF",
"created_at": "2019-11-12T23:34:03.012Z",
"updated_at": "2019-11-12T23:53:45.481Z",
"amount_money": {
"amount": 13080,
"currency": "USD"
},
"total_money": {
"amount": 14047,
"currency": "USD"
},
"processing_fee": [
{
"effective_at": "2019-11-13T01:53:44.000Z",
"type": "INITIAL",
"amount_money": {
"amount": 375,
"currency": "USD"
}
}
],
"status": "COMPLETED",
"source_type": "CARD",
"card_details": {
"status": "CAPTURED",
"card": {
"card_brand": "VISA",
"last_4": "",
"exp_month": ,
"exp_year": ,
"cardholder_name": "",
"fingerprint": "",
"bin": ""
},
"entry_method": "EMV",
"cvv_status": "CVV_NOT_CHECKED",
"avs_status": "AVS_NOT_CHECKED",
"auth_result_code": "009208",
"application_identifier": "A0000000031010",
"application_name": "CITI VISA",
"application_cryptogram": "6b7992ab9fba75fe",
"verification_method": "SIGNATURE",
"verification_results": "UNKNOWN",
"statement_description": ""
},
"location_id": "",
"order_id": "",
"employee_id": "DrU-af4--DVfMCkl2z73"
},
any help in the right direction would be appreciated!
See if something like this works for you
router.get('/tips', auth, (req, res) => {
try {
apiInstance.listPayments(opts).then(function (payments) {
const tips = payments.map(payment => payment.tip_money).filter(tip => tip != undefined);
res.send(tips);
})
} catch (error) {
console.error(error)
}
});
Remove the .filter at the end if you also want the endpoint to return the undefined tips since it doesn't seem like all the payments have tips on them.

How To: add new json content into a preexisting file following the same format inside an array

I am using Node.js for my server side and have passed back a json object to the server from teh client. I have gotten the data to add on to the end of the preexistin gfile, but i wan the data to be added into the file under the electricalAssest section.
This is the JSON file on the server side I wan tot add the data to.
{
"substation": [
{
"id": "1",
"geoLocation": "-33.7490, 84.3880",
"supportAssetTypes": [
{
"id": "cs-1",
"type": "capacitorStructure",
"specifications": {
"construction": "galvanized steel",
"capacity": {
"x": 10,
"y": 2,
"z": 5
}
}
}
],
"electricalAssetTypes": [
{
"id": "siemens-c1",
"type": "capacitor",
"specifications": {
"manufacture": "siemens",
"model": "1234",
"shape": "box",
"technology": "internally fused",
"ratedVoltage": 15,
"frequency": [
50,
60
],
"ratedPower": [
{
"kvar": 1000,
"frequency": 50
},
{
"kvar": 1200,
"frequency": 60
}
],
"maxCurrent": "180",
"BIL": [
95,
125,
150,
170,
200
],
"dielectric": "Polypropylene film and oil",
"impregnant": "Biodegradable PCB-free oil",
"dischargeResistor": [
"75 V/10 min",
"50 V/5 min"
],
"losses": 0.2,
"temperatureRange": [
-50,
55
]
}
}
],
"supportAssets": [
{
"id": "struct121",
"type": "cs-1",
"location": {
"x": 1,
"y": 1,
"z": 1
}
}
],
"electricalAssets": [
{
"id": "c1",
"assetType": "siemens-c1",
"radioChs": [
101
],
"installation": {
"supportAssetId": "struct121",
"slot": {
"x":"1",
"y":"1",
"z":"1"
}
},
"mounting": "horizontal"
},
{
"id": "c2",
"assetType": "siemens-c1",
"radioChs": [
102
],
"installation": {
"supportAssetId": "struct121",
"slot": {
"x":"2",
"y":"1",
"z":"1"
}
},
"mounting": "horizontal"
}
]
}]}
This is the function that calls adds the object to the end of the file in a long string.
router.post('', function(req, res, next) {
const token = req.headers['authorization'];
//const secretOrKey = 'your_jwt_secret';
if (!token) {
return res.status(401).send({auth: false, message: 'No token provided.'});
}
jwt.verify(token, 'your_jwt_secret', function(err, decoded) {
if (err) {
return res.status(401).send({auth: false, message: 'Failed to authenticate token.'});
}
else {
if (decoded.role === 'admin' || decoded.role === 'engineer') {
fs.readFile('configDB/configuration.json', (err, data) => {
if (err) throw err;
let json = JSON.parse(data);
let object = JSON.stringify(req.body);
//json.push('new capCan: ' + object);
fs.appendFile("configDB/configuration.json", JSON.parse(JSON.stringify(object)), function(err){
if(err) throw err;
console.log(object);
res.send({ status: 'success'});
});
})
}
else {
return res.status(500).send({admin: false, message: 'unauthorized to edit file'});
}
}
})
The code right now works but just adds the code to the very end of the file after the last "}". I want it to be inside the electricalAssets section in that same format.

Categories

Resources