get route only with specified parameter - mongodb

I am new to MongoDB and CRUD APIs.
I have created my first database and inserted some data. I can do get, post and delete requests.
Now I want to request a 'get' by adding a parameter, so I do the following:
router.get('/:story_name', async function (req, res, next) {
const selectedStory = await loadStoryToRead()
res.send(await selectedStory.find({}).toArray())
})
say that story_name is S1C1,
I can do http://localhost:3000/api/whatever/s1c1 to get the data.
I would have expected to retrieve the data ONLY by using the specified parameter, however I can use the ID or the date or any other parameter found in the json file to get the data.
for example I can do
http://localhost:3000/api/whatever/5d692b6b21d5fdac2... // the ID
or
http://localhost:3000/api/whatever/2019-08-30T13:58:03.035Z ... // the created_at date
and obtain the same result.
Why is that?
How can I make sure that if I use router.get('/:story_name' ... I can retrieve the data only if I use the 'story_name' parameter?
Thanks!
* UPDATE *
my loadStoryToRead() looks like this:
async function loadStoryToRead () {
const client = await mongodb.MongoClient.connect(
'mongodb+srv://...', {
useNewUrlParser: true
})
return client.db('read').collection('selectedStory')
}
I will try to reformulate my question.
I want to ensure that the data is retrieved only by adding the 'story_name' parameter in the URL and not by adding any other parameter within the file.
The reading that I have done suggested to add the parameter to the get request, but when I do it, it doesn't matter what parameter I enter, I can still retrieve the data.
The delete request, however, is very specific. If I use router.delete('/:id'... the only way to delete the file is by using the ID parameter.
I would like to obtain the same with a get request and not using the 'id' but by using 'story_name'.

you can use regular expression capabilities for pattern matching strings in queries.
Syntax is:
db.<collection>.find({<fieldName>: /<string>/})
for example, you can use
var re = new RegExp(req.params.story_name,"g");
db.users.find({$or:[{"name": re}, {"_id": re}, {..other fields}]});
You can use $and and $or according to your requirement.
To read more follow the link
https://docs.mongodb.com/manual/reference/operator/query/regex/

Related

How to set OpenAPI query parameter as array

I use openapi v2.
I read this document https://swagger.io/docs/specification/serialization/ .
I want to define path that take array and 1 value query parameter like below.(userIds and groupId)
/users{?userIds}{groupId}
But I call this url like below, it's return 404.
const url = '/user?userIds=10,11&groupId=1'
How to define it?

Netsuite - REST API - Making query with Token Based Authentication (TBA) - (in Python)

This is a follow up to the successful call using Netsuite Token Based Authentication (TBA) REST webservice,
I would like to get some guidance on how to perform a query.
I am supposed to read records like this (please see screenshot)
how can I perform a specifc query (by table for a list of records and also specific record) ?
https://gist.github.com/axilaris/4386c3537d04737d3775c156562b7545 <-- here is the python code for the TBA that has worked successful. I would like to know how to construct the next step on how to perform the query and read specific record (as shown in the screenshot).
This is a custom record with an ID like this customrecord1589
To query a specific record: You're going to need to create/ deploy a RESTlet in Netsuite similar to the following:
/**
* #NApiVersion 2.1
* #NScriptType Restlet
*/
define([
"N/log",
"N/search",
], function (log, search) {
function post(context) {
return JSON.stringify(getCustomRecords(context));
}
function getCustomRecords(context) {
log.debug('POST Context', context);
return search.lookupFields({
//Change CUSTOM_RECORD to the type of custom record you are querying
type: search.Type.CUSTOM_RECORD + '1589',
id: context.id,
columns: context.fields,
});
}
return {
post: post,
};
});
In your Python Script: Make sure you change the URL of the request to the deployment URL of this new RESTlet. Also, make sure to pass any parameters you need (like 'id' or 'fields' in my example) in your POST request payload. So instead of:
payload = {
"name":"value",
"foo":"bar",
"duck":"hunt",
}
pass
payload = {
"id":"9999999",
"fields": ["custrecord_field1", "custrecord_field2"],
}
where id is the internalid of the record you want to query and the fields array are the internalids of the fields you want values from.
If this goes successfully, the result should show up as conn.text in your python script!

Can I send any other parameter rather than id, to fetch Function of mongoose to get that specific data from mongodb

This is a fetch code, which is working fine to get the specific data from mongodb, like in the below code i got the specific year, but I wanted to send the parameter from my front end and based on that parameter I wanted to fetch, but the send parameter is not in req.body, although I get the parameter in create , update and delete functions, but not working in fetch func. I dont know why
export const getOfferedCourse = async(req,res) =>{ //it is time consuming task so this func is async
console.log('within controller',req.body);
try{
const course = await OfferedCourse.find({year:'2021'}).exec();
res.status(200).json(course);
}catch(error){
res.status(404).json({ message: error.message});
}
}
For sending a POST request with JSON body, you'll need to use the body-parser middleware to parse the request body into req.body
app.use(express.json());
For GET requests with query params, use req.query

Strapi - How to GET data sorted based on relation property?

I have an Articles table and it has a relation with the Authors table. Each author has a name property. I want to make a GET request for the articles and receive the articles sorted based on their author's name.
When I use _sort=author in the url parameters, I get the articles sorted based on the author object's ID.
When I use _sort=author.name in the url parameters, I get the articles in a seemingly random order but definitely not based on author.name.
How can I get the data sorted based on author.name?
I use mongoDB as my database.
That is the default behavior of _sort. However, you can simply accomplish this by overriding the find method in api/article/services/article.js to sort by Author's name like so:
module.exports = {
async find(params, populate) {
let result = await strapi.query('article').find(params, populate);
if (params._sort == 'author')
return result.sort((a, b) => (a.author.name > b.author.name) ? 1 : -1);
return result;
},
}
Check the documentation for customizing services to get more info: https://strapi.io/documentation/v3.x/concepts/services.html#concept

How to get all available field names in Facebook API (get_insights) method?

def get_campaigns_insight(self, start_date, end_date, batch_size):
params = {
'time_range': {'since':start_date,'until':end_date},
'filtering': [],
'level': 'campaign',
'breakdowns': ['country'],
'limit': batch_size,
'date_preset': 'lifetime',
}
fields = ['campaign_name', 'canvas_avg_view_percent']
response = self.account.get_insights(
fields=fields,
params=params,
)
data = str(response)
Currently I am passing the field names in a list and throwing it into the parameters as an argument, this works and i can manually add the names from the documentation, but surely there should be a way to get all the fields available right?
There is no way to get ALL fields, else a lot of users would use the oppertunity and use bandwith they do not really need - because you will most likely not need ALL fields. For all API calls, Facebook only returns a few default fields and additional fields you specify.