department {
"_id": "1",
"department": "Computers",
"type": "Department",
"room_no": "102",
"HOD": "Mr. G Rahul",
"floor": "1st Floor"
}
student {
"_id": "fdf370e2f43d4af1b505b8913502a5e4",
"_rev": "1-16df9a4cd45ca69009ab6c9767425a8e",
"student Name": "H Ravi",
"date_of_birth": "March 1, 1993",
"roll_no": "55",
"inter_marks": "820",
"secondary_marks": "420"
"department_id": "1",
"type": "student"
}
Map Function
function(doc) {
var id,department,student,hod,dob;
if(doc.type == 'student') {
id = doc.department_id;
dob = new Date(doc.date_of_birth)
student = doc;
}
}
emit(dob, {'_id': id,"student_doc": student});
}
After writing map function we call view by using URL "//localhost:5984/db_name/_design/design_name/_view/view_name". In that URL we will append ?include_docs=true after "view_name"("//localhost:5984/db_name/_design/design_name/_view/view_name/?include_docs=true") to get the docs of by using _id in emit, example: emit(dob,{"_id": id}) it will return the docs of linked id...My question is how can we access that docs in reduce function.
You can’t, the docs are fetched on query time, not on indexing time, so the reduce function never gets to see that data. Sorry!
Related
I have json data like this :
{
"people": [
{
"id": "1",
"company": "Blitz",
"fullName": "Chad anderson"
},
{
"id": "2",
"company": "NFZ",
"fullName": "surge bash"
},
{
"id": "3",
"company": "Ultimate Chad Company LLC",
"fullName": "George"
},
{
"id": "4",
"company": "Blitz",
"fullName": "Chad kuton"
},
{
"id": "5",
"company": "NFZ",
"fullName": "piguła"
},
]);
currently I have code like this:
function appendData(data) {
let tblBody = document.getElementById('tableWithContent');
let outPut = '';
data.sort((a,b) => a.company.localeCompare(b.company));
for(let person of data){
outPut += `<tr>
<td></td>
<td>${person.fullName}</td>
<td>${person.company}</td>
</tr>`;
}
tblBody.innerHTML = outPut;
};
I would like to display it in a way that :
Creates html table populated with companies and names of employess, within that company. In a way that if both workers have the same company , they are just displayed within that one company.
However, the code displays , and it displays workers in one column, and companies in another.
I would like to know if there is a neat way to use for example. reduce() method to that.
So when I fetch this data to html it displays all of the people from one company , then all of the people from another company (without displaying the companies of employees each time - if they are from the same company).
Building a react native app using CosmosDB and it's SQL api.
Per their documentation, I can add an object to a container like this:
const CosmosClient = require('#azure/cosmos').CosmosClient;
const client = new CosmosClient({ endpoint, key });
const myNewObject = {foo: "bar"}
await client
.database(databaseId)
.container(containerId)
.items.create(myNewObject);
And I can confirm this works.
What I'm trying to do tho, is place data into that {foo: "bar"} document that already exists.
So far I've tried chaining the .item method, but it does't work.
await client
.database(databaseId)
.container(containerId)
.item(idOfMyNewObject) // The existing object I want to create a child in
.item('myNewChildObject') // new child of the parent
.create(newEntry); // new entry in the new child
Any ideas? the documentation doesn't seem to talk about this.
There's no method on the container that does this for you. You must define the structure of the data yourself in your code. Here is an example of a customer record which has both an array of addresses as well as an embedded object.
const customer = {
"id": "000242A2-BF40-4220-864B-2770CAA38F5D",
"type": "customer",
"customerId": "000242A2-BF40-4220-864B-2770CAA38F5D",
"title": "",
"firstName": "Timothy",
"lastName": "Kelly",
"emailAddress": "timothy4#adventure-works.com",
"phoneNumber": "193-555-0189",
"creationDate": "2014-03-14T00:00:00",
"addresses": [
{
"addressLine1": "9918 Scottsdale Rd.",
"addressLine2": "",
"city": "Novato",
"state": "CA ",
"country": "US",
"zipCode": "94947",
"location": {
"type": "Point",
"coordinates": [
-122.764,
38.0852
]
}
}
],
"password": {
"hash": "LvEbgjonEPU11HEeSXqdzTsmqNeUfuhxBNL82vGlCWA=",
"salt": "61626BAE"
},
"salesOrderCount": 1
}
I am trying to display my seed data as JSON when a user visits a certain endpoint. I have two tables, Playlists and Favorites. It is a one to many relationship where a Playlist has many Favorites. The JSON should be formatted like this:
[{
"id": 1,
"playlist_name": "Favorite songs of all time",
"favorites": [{
"id": 1,
"name": "We Will Rock You",
"artist_name": "Queen",
"genre": "Rock",
"rating": 88
}]
}]
The function that I am calling to retrieve data from the database is this:
const connection = require("../connection");
function getAll() {
return connection.select().from('playlists').join('favorites', 'playlists.id', '=', 'favorites.id')
}
module.exports = getAll;
And what I get back when I call this function is this:
[
{
"id": 1,
"playlist_name": "chill_tunes",
"name": "Leo",
"artist_name": "John",
"genre": "Pop",
"rating": 42,
"playlist_id": 1
},
{
"id": 2,
"playlist_name": "good_vibes",
"name": "Dan",
"artist_name": "Deer",
"genre": "Rock",
"rating": 52,
"playlist_id": 1
},
{
"id": 3,
"playlist_name": "hump_day_happiness",
"name": "Nick",
"artist_name": "Legend",
"genre": "Rap",
"rating": 12,
"playlist_id": 2
}
]
I have no idea how to format my JSON data to get it like the code up top. Any help would be greatly appreciated.
You can use reduce
Here idea is
On op object create keys based on playlist id.
If there's already a key we push the new value to favourites
If not than we initialize favourites with {id, playlist_name , favourites:[]} and than push the new value
let arr = [{"id": 1,"playlist_name": "chill_tunes","name": "Leo","artist_name": "John","genre": "Pop","rating": 42,"playlist_id": 1},{"id": 2,"playlist_name": "good_vibes","name": "Dan","artist_name": "Deer","genre": "Rock","rating": 52,"playlist_id": 1},{"id": 3,"playlist_name": "hump_day_happiness","name": "Nick","artist_name": "Legend","genre": "Rap","rating": 12,"playlist_id": 2}]
let final = arr.reduce((op,{id, playlist_name ,name ,artist_name ,genre ,rating , playlist_id}) => {
op[playlist_id] = op[playlist_id] || {id, playlist_name , favourites:[]}
op[playlist_id].favourites.push({id, playlist_id ,name ,artist_name ,genre ,rating})
return op
},{})
console.log(Object.values(final))
I needed assistance in order to work out why the aggregate function is not responding the way I'd expect it to respond. This is a RESTful API service I've designed in which I am trying to connect collections with each other. Please note the following:
Collection: Season
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
Collection: Play
{
"_id": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
},
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
My implemented code in JavaScript
function getTestLookUp(db, collectionName, response, secondCollectionName){
console.log('First collection name: ' + collectionName + '\n' + 'Second collection name: ' + secondCollectionName);
db.collection(collectionName).aggregate([
{
$lookup:
{
from: secondCollectionName,
localField: 'PlayID',
foreignField: '_id',
as: 'requestedDetails'
}
}
]).toArray((err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
response.status(200).json({
'Items': res
});
}
});
}
The response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"requestedDetails": []
}
]
}
The things I've checked so far: the collection names are accurate, the ID is also accurate as I can search it up on the MLabs search feature. I don't understand as to why this is returning a empty 'requestedDetails' as I hoped it would return the item from the Play collection.
In addition to this, I would also appreciate if someone can point out how I can join multiple collections instead of 2.
I welcome any questions regarding this problem.
While still researching for this issue, I accidentally came across a another problem in which someone wrote a comment stating that "you might be comparing a String with ObjectID". This was the cause for this error as I obtain a String variable in return from the database and I am comparing the String variable with the _id which is expecting to see a ObjectID variable to complete the query. Therefore, meaning that my query/lookup is never matching these two variables.
The only way tackle this issue is to do a conversion (string to ObjectID) and then compare the values. However, since I'm using the version of ^3.1.10 of MongoDB, this functionality is not possible. Will need to update the version to 4.0 to be able to implement this functionality.
In order to rectify this issue, I managed to surround the foreign ID within $iod tags.
Before
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
After
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
}
}
Response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"Details": [
{
"_id": "5c0fc4aafb6fc04dd6ea4d81",
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
]
}
]
}
I'm an Italian PouchDb and AngularJS Developer.
My json document is:
{
"_id": "6",
"_rev": "3-f7283d7683cd6fb15753f494aad1d49f",
"name": "Ivrea",
"owners": [
{
"owner_id": 1,
"name": "asdas",
"address": "asdas",
"gender": "Uomo",
"type": "Assente",
"notes": [
]
},
{
"owner_id": 2,
"name": "balbaba",
"address": "blabla",
"gender": "Uomo",
"type": "Assente",
"notes": [
]
}
]
}
and after an ng-click action, I will delete owner_id: 2 object inside _id: 6 document. In API reference I found only document delete action, but not how to delete object inside document.
Thanks for your reply!!
Alessandro
You just need to put() the main document back in the database after you remove an object from it. :)
db.get('foo').then(function (doc) {
delete doc.whatever;
return db.put(doc);
}).catch(function (err) { /* ... */ });