Unable to retrieve documents in Cosmos DB stored procedure - javascript

I'm trying to retrieve documents matching an id through a simple SQL query in my JavaScript stored procedure. But it always returns that no document matches the id found. Tried all the things available in the Microsoft Documentation and the other StackOverflow answers. Here is my function:
function updateDocument () {
let context = getContext();
let collection = context.getCollection();
let collectionLink = collection.getSelfLink();
let response = context.getResponse();
tryQueryAndUpdate();
function tryQueryAndUpdate () {
var filterQuery = 'select * from user r WHERE r.id = "f5eddf33-7826-40c3-a634-9c349e5c7f73"';
let isAccepted = collection.queryDocuments(collectionLink, filterQuery, {}, function (err, documents, responseOptions) {
if (err) throw err;
if (documents.length > 0) {
console.log("Documents exists - " + documents.length);
} else {
// Else a document with the given id does not exist..
console.log("Document doesn't exist " + documents.length);
}
});
}
}
My document:
{
"firstName": "firstname",
"lastName": "lastname",
"email": "firstname.lastname#gmail.com",
"businessRole": "",
"functionalArea": null,
"type": "internal",
"status": "enable",
"modifiedDate": "2020-07-10T14:34:54.557Z",
"id": "f5eddf33-7826-40c3-a634-9c349e5c7f73",
"_rid": "H+pKAKZdGd0BAAAAAAAAAA==",
"_self": "dbs/H+pKAA==/colls/H+pKAKZdGd0=/docs/H+pKAKZdGd0BAAAAAAAAAA==/",
"_etag": "\"730103dd-0000-0100-0000-5f6302800000\"",
"_attachments": "attachments/",
"securityGroup": "c5d3dc10-bfa0-11ea-8394-48463089baf6",
"engagementId": "945acacf-a3ea-43ef-8e31-70576055ba4f",
"sort": {
"firstName": "firstname",
"lastName": "lastname"
},
"userStatus": "active",
"_ts": 1600324224
}
document:
container:
Any help would be appreciated. Thank you.
Execution parameters:
Console output:

Related

how to find data in nested array in mongodb and node js

i am trying to find corder data in below documents but i can not do this work if you know about how to find nested array data in below document so please find data for {corder}.
{
"_id": "63064232cf92b07e37090e0a",
"sname": "Bombay collection ",
"phone": 9963366555,
"costomer": [
{
"cname": "Ammar ",
"cphone": 919628497,
"ccity": "Palanpur",
"_id": "632ef012a9b88eb59d0210fa",
"corder": [
{
"clothType": "Pathani",
"prize": 236,
"date": "2022-09-24",
"status": "true",
"_id": "632ef078a9b88eb59d02110c"
}
],
}
],
},
and my code is id = "main document id" & obid ="cosomer id " & orid = " order id "
app.get('/getuser/:id/:obid/:orid', async (req, res) => {
try {
const id = req.params.id
const obid = req.params.obid
const orid = req.params.orid
console.log(id);
const peruserdata = await getschema.find({ 'costomer.corder': orid } ,
{ "_id": orid, "costomer.$.corder": { $elemMatch: { "_id": orid } } });
res.status(201).json(peruserdata);
} catch (error) {
console.log(error);
res.send(error)
}
})

How to check a propery of an object inside another object exist?

Using the following array with two objects that include another object inside I would like to know if there is a way to find which is the applicationID has applicantID equal with "5bd3480af09ddf0258c3a31d"
Array [
Object {
"__typename": "JobApplication",
"_id": "5be097753397465946e051fd",
"applicant": Object {
"__typename": "User",
"_id": "5bd83b9a62a9f33cf0f1033b",
},
},
Object {
"__typename": "JobApplication",
"_id": "5bdc7c8b3241cb5bc10ac694",
"applicant": Object {
"__typename": "User",
"_id": "5bd3480af09ddf0258c3a31d",
},
},
]
So in this case it has to return "5bdc7c8b3241cb5bc10ac694".
This are my two constants first will return the user id and second will return only the applications id.
const { _id } = this.props.getMe.me._id;
const applicationID = getJobApplicationsForThisJob.map(application => application._id);
I could check if the user id is in any of the objects like this
const applicantId = getJobApplicationsForThisJob.map(user => user.applicant._id);
const hasApplied = applicantId.includes(_id);
Thanks
You can use the .find method.
var item = arr.find(function(x) {
return x.applicant._id == find;
});
The find method returns the first found item or undefined if a record was not found.
var arr = [{
"__typename": "JobApplication",
"_id": "5be097753397465946e051fd",
"applicant": {
"__typename": "User",
"_id": "5bd83b9a62a9f33cf0f1033b",
}
}, {
"__typename": "JobApplication",
"_id": "5bdc7c8b3241cb5bc10ac694",
"applicant": {
"__typename": "User",
"_id": "5bd3480af09ddf0258c3a31d",
},
}];
var find = "5bd3480af09ddf0258c3a31d";
var item = arr.find(function(x) {
return x.applicant._id == find;
});
console.log(item != undefined ? item._id : "Not Found");
Since you are using Javascript, you would want to do something like my comment,
let _id = "5bd3480af09ddf0258c3a31d";
let list = []; //your list of objects.
let applicationResults = list.where( (app) => app.applicant._id = _id);
if (applicationResults.length == 0){
console.log("no applicantion with this applicant found.");
}else {
console.log("Found " + applicationResults.length + " Applications from this Applicant")
return applicationResults;
}

How to delete an item in a json file via http delete request in nodeJS?

So Basically, i have a JSON file which consists of user and group data. I want to delete a particular group. This is what my JSON file looks like:
authdata.json:
[{
"name": "Allan",
"role": ["Group Admin", "Super Admin"],
"group": ["Cool-Group", "ss"]
}, {
"name": "super",
"group": ["Nerd Group"],
"role": ["Super Admin"]
}, {
"name": "Terry",
"role": ["Group Admin"],
"group": ["Cool-Group"]
}, {
"name": "Kaitlyn",
"role": ["Group Admin"],
"group": ["Nerd-Group"]
}, {
"name": "Alex",
"role": ["Group Admin"],
"group": ["Cool-Group"]
}]
I'm just confused on how to handle a http delete request in nodeJS?
this how my angular component is sending the request to the server:
remove.component.ts:
RemoveGroup() {
this.httpService.delete < any > (this.apiURL + 'deletegroup', {
group: this.groups
}).subscribe(
data => {
if (data['success'] == true) {
alert(data.group + " is removed");
} else {
alert("No groups found");
}
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
}
This is the server side on NodeJS (reading the json file, assigning the data to a variable, trying to delete the group (which is not working for me) and writting back to the JSON file):
deletegroup.js:
app.delete('/api/deletegroup', (req, res) => {
// localhost:3000/api/auth?username=Terry
var groups = req.body.group;
var userObj;
fs.readFile('authdata.json', 'utf8', function(err, data) {
if (err) {
console.log(err);
//Some error happended opening the file. No Success
res.send({
'group': '',
'success': false
});
} else {
userObj = JSON.parse(data);
for (let i = 0; i < userObj.length; i++) {
for (let j = 0; i < userObj.length; j++) {
if (userObj[i].group[j] == groups) {
userObj.splice(userObj.indexOf(groups), 1);
//find first instance of user name and success
}
}
}
var newdata = JSON.stringify(userObj);
fs.writeFile('authdata.json', newdata, 'utf-8', function(err) {
if (err) throw err;
//Send response that registration was successfull.
res.send({
'group': groups,
'success': true
});
});
//no username was found that matched
}
});
});
I assume that the problem is not with HTTP DELETE request. The concern is with how to remove a child node. See the below code snippet. You can pass the groups as an array to the deleteGroup function and see the result.
var data = [{
"name": "Allan",
"role": ["Group Admin", "Super Admin"],
"group": ["Cool-Group", "ss"]
}, {
"name": "Terry",
"role": ["Group Admin"],
"group": ["Cool-Group"]
}];
function deleteGroup(groupArray) {
groupArray.map((needle)=>{
data.map((userObj) => {
if(userObj.group) {
userObj.group.map((groupName, index)=>{
if (groupName == needle){
userObj.group.splice(index)
}
});
} else {
console.log("No group present for this user.")
}
});
});
return data
}
//uncomment below line & run in console to see the results
//console.log(deleteGroup(["Cool-Group"]))
Try out directly in Jsbin - https://jsbin.com/pejidag/1/edit?js,console
Happy coding!

Only retrieve specific data from a row in DynamoDB using JavaScript

Using DynamoDb and the "read" function provided here how would I go about only retrieving specific items (e.g. only firstname, lastname and city)
I would probably have to add some kind of filter, however i was not able to find anything that I could use.
This is my table structure (with bpNumber being the primary key):
Item:{
"salutationCode": "02",
"lastName1": "Berg",
"firstName": "Anne",
"street": "Am Dächle",
"streetNumber": "22/2",
"zipcode": "33425",
"countryCode": "DE",
"city": "Hausen",
"bpNumber": 222,
"dateOfBirth": "1955-07-01",
"attri": [
{
"attri1":"nonono"
},
{
"attri2": "yeayeayea"
}
]
}
and this the "read" method I'm using:
read(){
var docClient = new AWS.DynamoDB.DocumentClient()
var table = "businessPartnersData";
var bpNumber = 222;
var params = {
TableName: table,
Key:{
"bpNumber": bpNumber
}
};
docClient.get(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
}
});
}
Thank you for you time!
You can use ProjectionExpression:
params.ProjectionExpression = "firstname, lastname, city";
This will only return these attributes in the resultset, for all items.

Split JSON API's object into chunks in express app

I want to separate my API's output into different pages. I want to call them like this: http://127.0.0.1:3000/api/articles/0/<API-TOKEN>
Which is returning the first page with 2-3, etc. articles.
Full code can be found here: https://github.com/DJviolin/horgalleryNode/blob/master/routes/api.js
I have dummy data JSON file:
[
{
"articles": [
{
"id": "0",
"url": "audrey-hepburn",
"title": "Audrey Hepburn",
"body": "Nothing is impossible, the word itself says 'I'm possible'!",
"category": "foo",
"tags": [ "foo" ]
},
{
"id": "1",
"url": "walt-disney",
"title": "Walt Disney",
"body": "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you.",
"category": "foo",
"tags": [ "foo", "bar" ]
},
{
"id": "2",
"url": "unknown",
"title": "Unknown",
"body": "Even the greatest was once a beginner. Don't be afraid to take that first step.",
"category": "bar",
"tags": [ "foo", "bar", "baz" ]
},
{
"id": "3",
"url": "neale-donald-walsch",
"title": "Neale Donald Walsch",
"body": "You are afraid to die, and you're afraid to live. What a way to exist.",
"category": "bar",
"tags": [ "foo", "bar", "baz" ]
}
]
},
{
"users": [
{ "name": "Admin" },
{ "name": "User" }
]
}
]
Which is called into my API router this way:
function fsAsync(callback) {
fs.readFile(__dirname + '/../public/articles/data.json', 'utf8', function(err, data) {
if (err) {
return callback(err);
}
callback(null, JSON.parse(data));
});
};
I calling every articles like this at this route: http://127.0.0.1:3000/api/articles/<API-TOKEN>
router.get('/articles/:token', function(req, res) {
fsAsync(function(err, data) {
if (err) {
return res.send(err);
}
var articles = data[0].articles;
var q = articles.filter(function (article) {
// return article.id === req.params.id;
return article && apiToken === req.params.token;
});
res.json(q);
});
});
However I want to separate this API's output into different pages when I rendering this API route: http://127.0.0.1:3000/api/articles/0/<API-TOKEN>
I tried to implement the array.slice method described here: https://stackoverflow.com/a/8495740/1442219
How can it be achieved?
Thank You!
Update:
One thing could cause problem if I spliting a JSON object into chunks, than it will need to parse everything from that object first, than decide where to split? What if user visiting the last page at 567? This means the code first have to query through millions of millions of line to return the wanted page? What if it's a database, not a JSON with dummy data? In sort, what are the best practices to return a specific page for a blog from JSON / Mongodb / etc. source?
Update 2:
This returns the first two article from the object:
// http://127.0.0.1:3000/api/articles/c/<API-TOKEN>
router.get('/articles/c/:token', function(req, res) {
fsAsync(function(err, data) {
if (err) {
return res.send(err);
}
var articles = data[0].articles;
var count = 0;
var countMultiply = count * 2;
var a = countMultiply + 0;
var b = countMultiply + 2;
var c = articles.slice(a, b);
console.log(c);
var q = c.filter(function (article) {
// return article.id === req.params.id;
return article && apiToken === req.params.token;
});
res.json(q); // (0*2+0=0, 0*2+2=2), (1*2+0=2, 1*2+2=4), (2*2+0=4, 2*2+2=6), (3*2+0=6, 3*2+2=8)
});
});
How can I automate this able to use 0, 1, 2, 3 for page separators? So the first page at http://127.0.0.1:3000/api/articles/0/<API-TOKEN> URL to return articles (0,2) and the second page at http://127.0.0.1:3000/api/articles/1/<API-TOKEN> URL to return articles (2,4)?
Update 3:
Looks like it's working:
// http://127.0.0.1:3000/api/articles/page/0/<API-TOKEN>
router.get('/articles/page/:id/:token', function(req, res) {
fsAsync(function(err, data) {
if (err) {
return res.send(err);
}
var articles = data[0].articles.reverse();
var count = req.params.id; // Page number
var multiplier = 2; // Posts per page
var countResult = count * multiplier;
var a = countResult + 0;
var b = countResult + multiplier;
var c = articles.slice(a, b);
var pagesLength = articles.length / multiplier;
var pagesLengthCeil = Math.ceil(pagesLength); // Sum of all pages
console.log('pagesLengthCeil: ' + pagesLengthCeil);
console.log(c);
var q = c.filter(function (article) {
// return article.id === req.params.id;
return article && apiToken === req.params.token;
});
res.json(q); // (0*2+0=0, 0*2+2=2), (1*2+0=2, 1*2+2=4), (2*2+0=4, 2*2+2=6), (3*2+0=6, 3*2+2=8)
});
});
But I still don't know is it an efficient way to do this with huge JSON files or a database?

Categories