Nested Documents in FaunaDB - faunadb

I am just starting Fauna and FQL. How do we add a nested document inside another document using the online shell?
This is what I have so far
users: [
{
userID: "from google",
userName: "from signup form",
userEmail: "from signup form form",
profileimgurl: "maybe from google",
accessCode: 12345,
role: "main or secondary. customer will automatically become main."
},
{
userID: "from google",
userName: "from signup form",
userEmail: "from signup form form",
profileimgurl: "maybe from google",
accessCode: 12345,
role: "main or secondary. customer will automatically become main."
}
]

Fauna stores data in schemaless Documents, so you can embed arrays or other objects within the Document's data. For example, from the shell:
Create(
Collection("users"),
{
data: {
name: "Paul",
email: "paul#paul.com
address: {
country: "United States",
},
tags: ["pinball", "camping"]
}
}
)
Depending on how you need to read and update your documents, it may be appropriate to save data in a separate collection and maintain relationships with References.
Create(
Collection("public_profiles"),
{
data: {
name: "Paul",
tags: ["pinball", "camping"]
}
}
)
{
ref: Ref(Collection("public_profiles"), "307924242117165124"),
ts: 1629918291110000,
data: { name: "Paul", tags: ["pinball", "camping"] }
}
Update(
Ref(Collection("users"), "307924248572638574"),
{
data: {
tags: null,
profile: Ref(Collection("public_profiles"), "307924242117165124")
}
}
)
The Docs have a Social Graph example that demonstrates how to create and query relationships.

Related

Join two collection in mongodb

I'm new in mongodb. Could you please tell me how to perform join operation in this. I've two collection:
Collection 1 ("user")
{
_id: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
userName: "XYZ User",
age: 12
}
Collection 2 ("square")
{
_id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
side: 4,
area: 16
}
Now I want to retrieve the data from collection 2 is like this.
Expected output:
{
_id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
userName: "XYZ User",
side: 4,
area: 16
}
Thanks in advance :)
Here's one way to do it.
db.square.aggregate([
{
"$lookup": {
"from": "user",
"localField": "userId",
"foreignField": "_id",
"as": "userDoc"
}
},
{
"$set": {
"userName": {
"$first": "$userDoc.userName"
}
}
},
{ "$unset": "userDoc" }
])
Try it on mongoplayground.net.
You can keep the first documentid (_id) in the second document as userId for refrence and after that, you can use the join feature supported by MongoDB 3.2 and later versions. You can use joins by using an aggregate query.
You can do it using the below example :
db.user.aggregate([
// Join with square table
{
$lookup:{
from: "square", // other table name
localField: "_id", // name of user table field
foreignField: "userId", // name of square table field
as: "square" // alias for userinfo table
}
},
{ $unwind:"$user_info" }, // $unwind used for getting data in object or for one record only
// define some conditions here
{
$match:{
$and:[{"userName" : "XYZ User"}]
}
},
// define which fields are you want to fetch
{
$project:{
_id: 1,
userId: "$square.userId",
userName: 1,
side: "$square.side",
area: "$square.area"
}
}
]);
The Result will be
{
_id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
userName: "XYZ User",
side: 4,
area: 16
}
Cheers

How to create or update many-to-many relation in Prisma?

I have the following models, and many-to-many relation between them:
model User {
id String #id #default(cuid())
name String?
email String? #unique
followings Artist[]
}
model Artist {
id String #id #default(cuid())
name String #unique
spotifyId String #unique
followers User[]
}
When a user logs into my app, I retrieve their current followed artists, and need to update my database.
I have managed to select artists data from database (for updating user <-> artist relation), sample data:
const followings = [
{
id: '...',
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A'
},
{
id: '...',
name: 'Dua Lipa',
spotifyId: '6M2wZ9GZgrQXHCFfjv46we'
},
]
Now, this is my user object:
const user = {
id: 'someId',
name: 'someName',
email: 'someEmail'
}
I tried to insert or update user <-> artist relation with this query but I'm getting Bad Request error:
await prisma.user.upsert({
where: {
email: user.email
},
create: {
name: user.name,
email: user.email,
followings: {
connectOrCreate: followings
}
},
update: {
followings: {
connectOrCreate: followings
}
}
})
Please advise what I need to do. Thanks in advance.
P.S. I took the idea of the query from Updating a many-to-many relationship in Prisma post, but it didn't work for me, so please don't mark duplicate.
connectOrCreate should specify where key with id (so Prisma could find this entity) and create key with all required model fields (so Prisma could create it if it not already present), but you just passing an array of models. Change your code to this one:
await prisma.user.upsert({
where: {
email: 'user.email',
},
create: {
name: 'user.name',
email: 'user.email',
followings: {
connectOrCreate: [
{
create: {
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
},
where: { id: '...' },
},
],
},
},
update: {
followings: {
connectOrCreate: [
{
create: {
name: 'MARINA',
spotifyId: '6CwfuxIqcltXDGjfZsMd9A',
},
where: { id: '...' },
},
],
},
},
});

How do I create an artifact with Multi-Value field type?

I'm trying to programatically create a User Story in Rally with pyral. We have some custom fields set up, e.g Client Name, which is a Drop-Down List (Multi-Value), for regular fields I'm able to provide the value as {key: value pairs} (e.g {"Priority": "High"}). How do I work with Multi-Value fields?
When I pass string I get "Error 421 Client Name cannot be null", when I pass an array, it doesn't work either.
c_ClientName: {
_rallyAPIMajor: "2",
_rallyAPIMinor: "0",
_ref: "https://rally1.rallydev.com/slm/webservice/v2.0/HierarchicalRequirement/331721021908/c_ClientName",
_type: "AllowedAttributeValue",
_tagsNameArray: [
{
Name: "Client one",
_ref: "/allowedattributevalue/1234567"
},
{
Name: "Client two",
_ref: "/allowedattributevalue/1234568"
},
{
Name: "Client three",
_ref: "/allowedattributevalue/1234569"
}
],
Count: 3
}
This is what a typical read of existing User stories look like.

Foursquare API Lists -> ListItems -> ?Venues?

Via the foursquare API and documentation, i'm trying to extract venues from lists.
I'm hitting getting a list response, which has listItems, which is suppose to be "count and items of list items on this list."
What the API responds with is just the count.
{
id: "510ae78ae4b0607cd8d8504f"
name: "Brunchn'"
description: ""
user: {
id: "157255"
firstName: "Jon"
lastName: "Doe"
gender: "male"
relationship: "self"
photo: {
prefix: "https://irs3.4sqi.net/img/user/"
suffix: "/POOIJDBXTTRPSB0.jpg"
}
}
editable: true
public: true
collaborative: false
url: "https://foursquare.com/jon_doe/list/brunch"
canonicalUrl: "https://foursquare.com/jon_doe/list/brunch"
createdAt: 1359669130
updatedAt: 1364583099
followers: {
count: 0
}
listItems: {
count: 3
}
}
from the documentation, if i get the item response, I can retrieve the venue, but there doesn't seem to be a connection, or i'm going at this from the wrong API call. Anyone have any suggestions?
The call is https://api.foursquare.com/v2/users/self/lists

Ember-data building relationships without ids

I'm trying to build an Ember application with a MongoDB backend. Ember-data now supports embedded objects which makes it really easy and great to be able to pull the objects right out of the nested document.
My problem is in figuring out how to relate objects to each other.
Lets look at an example of a class room with students and assignments.
{
students: [
{ name: 'Billy' },
{ name: 'Joe' }
],
assignments: [
{ name: 'HW1', score: 70, student_name: 'Billy' },
{ name: 'HW2', score: 80, student_name: 'Billy' },
{ name: 'HW1', score: 60, student_name: 'Joe' },
{ name: 'HW2', score: 75, student_name: 'Joe' }
]
}
How would I build a relationship for the student so that I could pull back all of their assignments?
Related, I'm trying to figure out how to relate objects that are nested inside each other. I created a jsbin trying to build a relationship between nested objects (going up the tree rather than just down) but I'm not sure how to do it.
You can use the repo below to guide you on how to do embedded association. Though they are not using mongodb, the important thing is on the ember-data side, they are doing embedded association.
https://github.com/dgeb/ember_data_example/blob/master/app/assets/javascripts/controllers/contact_edit_controller.js
Note that here App.PhoneNumber is embedded in App.Contact. But it should give you an idea on how to go abut resolving yours.
App.Contact = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
email: DS.attr('string'),
notes: DS.attr('string'),
phoneNumbers: DS.hasMany('App.PhoneNumber'),
});
App.PhoneNumber = DS.Model.extend({
number: DS.attr('string'),
contact: DS.belongsTo('App.Contact')
});
https://github.com/dgeb/ember_data_example/blob/master/app/assets/javascripts/store.js
App.Adapter = DS.RESTAdapter.extend({
bulkCommit: false
});
App.Adapter.map('App.Contact', {
phoneNumbers: {embedded: 'always'}
});
App.Store = DS.Store.extend({
revision: 12,
adapter: App.Adapter.create()
});
https://github.com/dgeb/ember_data_example/blob/master/app/assets/javascripts/controllers/contact_edit_controller.js
App.ContactEditController = Em.ObjectController.extend({
needs: ['contact'],
startEditing: function() {
// add the contact and its associated phone numbers to a local transaction
var contact = this.get('content');
var transaction = contact.get('store').transaction();
transaction.add(contact);
contact.get('phoneNumbers').forEach(function(phoneNumber) {
transaction.add(phoneNumber);
});
this.transaction = transaction;
},
save: function() {
this.transaction.commit();
},
addPhoneNumber: function() {
this.get('content.phoneNumbers').createRecord();
},
});