I have a prisma query that returns users on a pivot table CommunityMember. The pivot table associates to the table User. As a result, my queries into the User table do not place the object user on top of the replies. I have a lot of functions designed to run with the user object on top so I am trying to figure out how to map user into my returns so the functions can run correctly. I've tried a lot of combinations of map and have had no luck. Do you all have any ideas?
Here is my prisma query:
members = await prisma.user.findMany({
select: {
id: true,
username: true,
name: true,
bio: true,
avatar: true,
},
skip: 10 * Number(page),
take: 10,
});
It gives a result like
members:
[{id: 2, username: 'man}, {id: 3, username: 'dan'}]
I want it to look like: members:
members:
[{user: {id: 2, username: 'man'}}, {user: {id: 3. username: 'dan'}}]
If I run members[0].user I should get the data inside. It seems like a simple map function, but I have not been able to get it to work.
Another example of what I get, but do not want.
members: [
{
id: 2,
username: 'man',
name: 'A Man',
bio: 'A man.',
avatar: [Object]
},
{
id: 3,
username: 'dude',
name: 'Dude',
bio: "Dude is a #1 developer.",
avatar: [Object]
},
This is what I want.
members: [
{
//Notice the user object on top of each entry
user: {
id: 2,
username: 'man',
name: 'A Man',
bio: 'Man.',
avatar: [Object]
}
},
{
user: {
id: 3,
username: 'dude',
name: 'Dude',
bio: "Dudes a #1 developer.",
avatar: [Object]
}
},
]
Not sure I got the whole picture but wouldn't this do?
const members = [
{
id: 2,
username: 'man',
name: 'A Man',
bio: 'A man.',
avatar: {}
},
{
id: 3,
username: 'dude',
name: 'Dude',
bio: "Dude is a #1 developer.",
avatar: {}
}
].map(member => ({user: member}))
if your object looks like:
obj = {members: [{...}, ..]}
then an Array.map will solve the problem:
const userMembers = obj.members.map((member) => ({user: member});
obj.members = userMembers;
Related
How to get data from an object? I need to get data from dataValues and write it down
const user = User.findOne({
}).then(e=>console.log(e))
User {
dataValues: {
id: 1,
firstName: 'Мен',
lastName: 'Bezrukov',
login: 'qqq',
password: '1234',
role: 'admin',
ip: '12345',
descipt: 'developer',
o_sebe: 'top man',
soc_set: 'vk',
age: '17',
likes__foto: '5',
coment__foto: null,
createdAt: 2023-01-15T09:06:39.000Z,
updatedAt: 2023-01-15T09:07:00.000Z
},
_previousDataValues: {
id: 1,
firstName: 'Мен',
lastName: 'Bezrukov',
login: 'qqq',
password: '1234',
role: 'admin',
ip: '12345',
descipt: 'developer',
o_sebe: 'top man',
soc_set: 'vk',
age: '17',
likes__foto: '5',
coment__foto: null,
createdAt: 2023-01-15T09:06:39.000Z,
updatedAt: 2023-01-15T09:07:00.000Z
},
uniqno: 1,
_changed: Set(0) {},
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [
'id', 'firstName',
'lastName', 'login',
'password', 'role',
'ip', 'descipt',
'o_sebe', 'soc_set',
'age', 'likes__foto',
'coment__foto', 'createdAt',
'updatedAt'
]
},
}
You can access directly the data by user.id, user.firstName or destructuring:
const {id,firstName} = user
another options is putting raw: true.
User.findOne({ where: {firstname: "some name"},
raw: true
})
This gives you directly an object with only the data instead of an sequelize instance.
In a project I'm working on, I need to merge 2 arrays of objects and as a result one new array of objects containing the merged key/values where two Ids match.
To give an example I created the following snippet but is not fully correct on what I want to achieve. More details after the snippet
const users = [{
id: 'Ae7uWu7LjwoEgVqzFU5xc',
firstName: 'Carl',
lastName: 'Jones'
},
{
id: 't2wzj8dh4r-qw1_SW-IOE',
firstName: 'Chloe',
lastName: 'Kearney'
},
{
id: '50Zwvw37OejbQBG7csZWJ',
firstName: 'Gemma',
lastName: 'Sloan'
},
{
id: 'NpcXdEKqfzhVCZOJ1dKuw',
firstName: 'Dario',
lastName: 'Angelini'
},
{
id: 'e95ZG9IfV442HdJp-CaBL',
firstName: 'Mindy',
lastName: 'Schreiber'
},
{
id: 'eAMv8AbynYRkdBPE5Scm2',
firstName: 'Xdax',
lastName: 'Rufq'
},
{
id: 'egMXnFvoMM7f4in3Se4Ui',
firstName: 'Mtajx',
lastName: 'Plde'
},
{
id: '6kbPT-HC5-szACuJ85I6r',
firstName: 'Zsofi',
lastName: 'Toke'
}
]
const comments = [{
content: 'Patient follow up call scheduled for 11Nov2021 at 8am',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:11.780Z'
},
{
content: 'Patient confirmed GP referral on [date]',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:42.237Z'
},
{
content: 'Candidate called on [date] and visit scheduled for [date] ',
stage: 'AT_SITE',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:43:42.140Z'
},
{
content: 'Candidate test result was positive for Pompe disease on [date]',
stage: 'AT_SITE',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:45:21.716Z'
}
]
const result = users.map(t1 => ({
...t1,
content: comments.filter(t2 => t2.userId === t1.id).map(t1 => t1.content),
created: comments.filter(t2 => t2.userId === t1.id).map(t1 => t1.createdAt),
}));
console.log(result)
The result I was able to get from that try was an array of objects but the comments are represented as an array inside the user object itself as for the createdAt
this is an example of what I'm getting now
[{
"id": "t2wzj8dh4r-qw1_SW-IOE",
"firstName": "Chloe",
"lastName": "Kearney",
"content": [
"Patient follow up call scheduled for 11Nov2021 at 8am",
"Patient confirmed GP referral on [date]",
"Candidate called on [date] and visit scheduled for [date] ",
"Candidate test result was positive for Pompe disease on [date]"
],
"created": [
"2021-10-29T11:41:11.780Z",
"2021-10-29T11:41:42.237Z",
"2021-10-29T11:43:42.140Z",
"2021-10-29T11:45:21.716Z"
]
},]
What I would like to get is the way around, I mean I want the comments to include the
firstName and lastName of the user when the comments.userId is equal to the users.id
Example of the goal I want to achieve
consider the 2 objects below
comments = [{
content: 'Patient follow up call scheduled for 11Nov2021 at 8am',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:11.780Z'
},
{
content: 'Patient confirmed GP referral on [date]',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:42.237Z'
}, { ...some other comments...}]
users = [
{
id: 't2wzj8dh4r-qw1_SW-IOE',
firstName: 'Chloe',
lastName: 'Kearney'
},
{ ...some other users... }]
The result I'm seeking after the 2 objects are merged is as follows
res = [
{
firstName: 'Chloe',
lastName: 'Kearney',
content: 'Patient follow up call scheduled for 11Nov2021 at 8am',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:11.780Z'
},
{
firstName: 'Chloe',
lastName: 'Kearney',
content: 'Patient confirmed GP referral on [date]',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:42.237Z'
}
]
As above I'm adding the first and last name of the user with the comments where there is an Ids match, so they are together after the merging.
I'm looking to understand a good way of doing this
const comments = [{
content: 'Patient follow up call scheduled for 11Nov2021 at 8am',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:11.780Z'
},{
content: 'Patient confirmed GP referral on [date]',
stage: 'AT_CALLCENTER',
userId: 't2wzj8dh4r-qw1_SW-IOE',
createdAt: '2021-10-29T11:41:42.237Z'
}];
const users = [{
id: 't2wzj8dh4r-qw1_SW-IOE',
firstName: 'Chloe',
lastName: 'Kearney'
}];
console.log(
comments.map(comment => {
const {id, ...user} = users.find(({id}) => id===comment.userId);
return ({...user, ...comment});
}));
I need to set an array for objects to firestore but only the first index of urls is getting stored. Any help in the right direction would be helpful thanks.
Code:
const object = [
{
user: 'mike',
userName: 'Mike nick',
Urls:[
{comment: "BBBBB", imageUrl: "url1"},
{comment: "BBBJvuyiu", imageUrl: "url2"},
{comment: "AAAAA", imageUrl: "url3"},
],
date: 'March 20th'
}
]
firestoreRef
.collection('users')
.doc(userId)
.collection('images')
.doc('customers')
.collection('customerExperience')
.doc(userId)
.set(object, { merge: true })
need this structure as user may continue to add more data:
it looks like this when i upload the object.
Your const object is actually an Array, when it should be an Object (that is not an Array).
The following should work:
const object = {
user: 'mike',
userName: 'Mike nick',
urls: [
{ comment: 'BBBBB', imageUrl: 'url1' },
{ comment: 'BBBJvuyiu', imageUrl: 'url2' },
{ comment: 'AAAAA', imageUrl: 'url3' }
],
date: 'March 20th'
};
Note the difference with your object:
const object = [
{
.....
}
]
UPDATE following your comment:
If you want to have it saved exactly the way you show in your updated question, do as follows. I am not sure however that this is the best way to save your data: as a matter of fact you are not creating an array but several fields of type "map" with the following names: 0, 1, etc.
One of the main (negative) side effect is that you will need to know all the fields names upfront in order to read them, while with a "genuine" Array field, you can loop over its values.
const object = {
0: {
user: 'mike1',
userName: 'Mike nick',
urls: [
{ comment: 'BBBBB', imageUrl: 'url1' },
{ comment: 'BBBJvuyiu', imageUrl: 'url2' },
{ comment: 'AAAAA', imageUrl: 'url3' }
],
date: 'March 20th'
},
1: {
user: 'mike2',
userName: 'Mike nick',
urls: [
{ comment: 'BBBBB', imageUrl: 'url1' },
{ comment: 'BBBJvuyiu', imageUrl: 'url2' },
{ comment: 'AAAAA', imageUrl: 'url3' }
],
date: 'March 20th'
}
};
From the Official Documentation, here's the sample code for the different data types:
let data = {
stringExample: 'Hello, World!',
booleanExample: true,
numberExample: 3.14159265,
dateExample: admin.firestore.Timestamp.fromDate(new Date('December 10, 1815')),
arrayExample: [5, true, 'hello'],
nullExample: null,
objectExample: {
a: 5,
b: true
}
};
You will need the following to create an object that contains an array of objects
let object = {
user: 'mike',
userName: 'Mike nick',
urls: {
[{comment: 'BBBBB', imageUrl: 'url1'},
{comment: 'BBBJvuyiu', imageUrl: 'url2'},
{comment: 'AAAAA', imageUrl: 'url3'}]
},
date: 'March 20th'
};
Let me know if this works for you.
I've the following complex JSON object that has got array and array inside an array. How can parse those arrays and create an object array for each element in the array. I'm using lodash library in my project, just in case if there are any functions available.
{
studentId: 123
name: XYZ
phone: 34234234
gender: M
subjects: [{
studentId: 123
subjectName: Math
scores:50
assignments:[
{
type: Internal,
submitted: yes,
status: failed
},
{
type: External,
submitted: yes,
status: passed
}]
},
{
studentId: 123
subjectName: Science
score: 20
assignments:[
{
type: Internal,
submitted: yes,
status: passed
},
{
type: External,
submitted: yes,
status: failed
}]
}]
}
Expecting:
[{
studentId:123,
name: XYZ
phone: 34234234
gender: M,
subjectName: Math
scores:50
assignments:[
{
type: Internal,
submitted: yes,
status: failed
},
{
type: External,
submitted: yes,
status: passed
}]
},
{
studentId:123,
name: XYZ
phone: 34234234
gender: M,
subjectName: science
scores:20
assignments:[
{
type: Internal,
submitted: yes,
status: failed
},
{
type: External,
submitted: yes,
status: passed
}]
}
]
You can use omit to get the details of the student without the subjects array, use these details to transform each item in the subjects array using defaults through map.
var details = _.omit(data, 'subjects');
var result = _.map(data.subjects, function(subject) {
return _.defaults({}, details, subject);
});
var data = {
studentId: '123',
name: 'XYZ',
phone: '34234234',
gender: 'M',
subjects: [{
studentId: '123',
subjectName: 'Math',
scores: 50,
assignments: [{
type: 'Internal',
submitted: 'yes',
status: 'failed'
},
{
type: 'External',
submitted: 'yes',
status: 'passed'
}
]
},
{
studentId: '123',
subjectName: 'Science',
score: 20,
assignments: [{
type: 'Internal',
submitted: 'yes',
status: 'passed'
},
{
type: 'External',
submitted: 'yes',
status: 'failed'
}
]
}
]
};
var details = _.omit(data, 'subjects');
var result = _.map(data.subjects, function(subject) {
return _.defaults({}, details, subject);
});
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
I encourage you to use Normalizr package. It's very useful and takes all care about your collections even if they're nested.
What is the best practice for structuring the state object in Redux in relation to related objects.
Example:
User has-one Organisation
With the above schema, where we also have a list of organisations is the following example a good idea?
{
user: {
id: 1,
organisation_id: 3,
first_name: 'Andrew',
last_name: 'McLagan',
email: 'andrew#example.com',
organisation: {
name: 'Foo Bar Co.'
suburb: 'Booklyn',
phone: '123-123-000',
},
},
orgnaisations: [
{
id: 1,
name: 'Facebook'
suburb: 'Booklyn',
phone: '000-000-000',
},
{
id: 2,
name: 'Twitter'
suburb: 'Manhattan',
phone: '456-456-000',
},
{
id: 3,
name: 'Foo Bar Co.'
suburb: 'Booklyn',
phone: '123-123-000',
},
{
id: 4,
name: 'Some Org.'
suburb: 'Bronx',
phone: '642-642-000',
},
]
}
Or would it be better to access the users organisation by:
const organisation = state.organisations[user.organisation_id];
I think it is better to access the user organizations through their ID. Here is a possible way to organize your state:
{
user: {
id: 1,
first_name: 'Andrew',
last_name: 'McLagan',
email: 'andrew#example.com',
organization: 3,
},
organizations: {
1: {id: 1, name: 'Facebook', suburb: 'Booklyn', phone: '000-000-000',},
2: {id: 2, name: 'Twitter', suburb: 'Manhattan', phone: '456-456-000'},
3: {id: 3, name: 'Foo Bar Co.', suburb: 'Booklyn', phone: '123-123-000'},
4: {id: 4, name: 'Some Org.', suburb: 'Bronx', phone: '642-642-000'},
}
}
Using vanilla Redux
If you want to get the current user and his organization, you can use the following selector:
function mapStateToProps(state) {
return {
user: state.user,
organization: state.organizations[state.user.organization]
}
}
The direct access using its ID will be a performance win. You can still easily query all stored organizations:
function mapStateToProps(state) {
return {
organizations: Object.values(state.organizations),
}
}
Using reselect
If you care about performance, using reselect would be a huge win. The first step is to define your selectors:
// Get a list of all organizations
const getAllOrganizations = createSelector(
state => state.organizations,
orgs => Object.values(orgs)
)
// Get the current user
const getUser = state => state.user
// Get the current user's organization
const getUserOrganization = createSelector(
[
state => state.user,
state => state.organizations,
],
(user, orgs) => orgs[user.organization],
)
You could now use those selectors to update your mapStateToProps functions. The two described above would be:
// Get the current user and his organization
function mapStateToProps(state) {
return {
user: getUser(state),
organization: getUserOrganization(state),
}
}
// Get all organizations
const mapStateToProps = getAllOrganizations