PRISMA 2.0 - I need help to delete a record inside a field with relationship list - prisma2

i am on this challange since Monday... please help me? Check my models.
model User {
id String #id #default(cuid())
bookmarks Home[] #relation(name: "UserBookmarks")
}
model Home {
bookmarkedBy User? #relation(name: "UserBookmarks", fields: [userId], references: [id])
userId String?
}
This example is: ONE PERSON can have MULTIPLE Homes in their BOOKMARKS, ok?
My PATCH it works fine, check above.
const home = await prisma.home.update({ where: { id: "123" }, data: { userId: "my-user-id", }, });
When i see the content in PRISMA STUDIO... works fine... i have a list of Homes in bookmarks field. PERFECT.
BUT NOW... how i can DELETE a BOOKMARK in this CASE?
i tried eveything... but i cant understand how i can do that :-( I tried this code bellow:
const home = await prisma.home.delete({ where: { userId: "my-user-id", }, });
AND
const user = await prisma.user.delete({ where: { bookmarks: "my-home-id", }, });
In this case Above... appears this message:
{
"message": "\nInvalid prisma.home.delete() invocation:\n\n{\n where: {\n userId: 'cl3he5om60008you1geu5hbpa'\n ~~~~~~\n }\n}\n\nUnknown arg userId in where.userId for type HomeWhereUniqueInput. Did you mean id? Available args:\ntype HomeWhereUniqueInput {\n id?: String\n}\n\n"
}
HELP ME GUYS!
Thanks guys

Related

How to update composite type model in Prisma?

I am trying to implement updation in a composite-type model in Prisma.
Here is my data structure:
{
"name":"toy",
"data":{
"sports":{
"currentState":"false"
},
"business":{
"currentState":"false"
}
}
}
Here I my code for updating:
const updatedSource = await prisma.sources.update({
where: {
name: 'toy'
},
data: {
data: {
sports: {
currentState: "true"
}
}
},
})
Here is my schema file
type SourcesData {
business SourcesDataState
sports SourcesDataState
}
type SourcesDataState {
currentState StateData[]
}
type StateData {
title String
url String
}
model sources {
id String #id #default(auto()) #map("_id") #db.ObjectId
data SourcesData
name String #unique
}
When I execute the above logic I get error as:Unknown arg `sports` in data.data.sports for type SourcesDataUpdateEnvelopeInput. Did you mean `set`? Available args:
Please guide what I am missing while updating.
The TypeScript should be pretty helpful in telling you what arguments you can or cannot use when interacting with Prisma. I strongly recommend using a code editor that includes TypeScript typehinting/Intellisense so you can see errors and warnings about your TypeScript usage as you are developing with Prisma.
Where it says Available args in your error, that should tell you the arguments that prisma.sports.update actually expects. If I had to guess (this may not be accurate, but you HAVE to look at the TypeScript to know exactly what it's supposed to be), it should look something like this:
const updatedSource = await prisma.sources.update({
where: {
name: 'toy'
},
data: {
data: {
update: {
sports: {
update: {
currentState: {
set: ["true"]
}
}
}
}
}
},
})
I strongly recommend reading Prisma's documentation on updating related/nested records: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#update-a-specific-related-record
let typeEncounter = await prisma.encounter.update({
where: {
id
},
data: {
[property]: {
update: {
[subProperty] : value,
},
},
},
}
)
I get a receive the error Unknown arg update in data..update
I have seen some people mention nesting updates but no official documentation and can't seem to get this straightened out. Anybody have any ideas? The property and subproperty are largely irrelevant here, just examples. The code works fine aside from updated a subfield of a type (mongoDB prisma). Without the update the entire type gets overwritten rather than the selected field.

Find record with an empty relation

Say I have this prisma schema with an implicit m:n-relation of Post and Tag
model Post {
id String #id
tags Tag[]
}
model Tag {
id Int #id #default(autoincrement())
posts Post[]
}
How do I find the first Post that has no associated Tags?
prisma.post.findFirst({
where: {
tags: {
// are nonexistent (something like count === 0?)
},
},
}),
Thanks for the help :)
You can probably use orderBy by count of tags in ascending order and get the first one? Like that:
prisma.post.findFirst({
orderBy: { tags: { _count: 'asc' } },
});
Searching on the internet I've found a link where the official documentation gives information on how to manage lists --> here
There it gives this example:
const posts = await prisma.post.findMany({
where: {
tags: {
isEmpty: true,
},
},
})
Try adapting that to your own situation.

count self relation on Prisma error: table name specified more than once

I am trying to count a self relation (followers) in Prisma2 (using PostgreSQL)
Model:
model User {
id String #id #default(cuid())
following User[] #relation(name: "UserFollows")
followers User[] #relation(name: "UserFollows")
}
Query:
const user = await prisma.user.findUnique({
where: { id: userId },
include: {
_count: {
select: { followers: true, following: true },
},
},
});
(using previewFeatures = ["selectRelationCount"]) and getting the following error:
Invalid prisma.user.findUnique() invocation:
Error occurred during query execution: ConnectorError(ConnectorError
{ user_facing_error: None, kind: QueryError(Error { kind: Db, cause:
Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code:
SqlState("42712"), message: "table name "User" specified more than
once", detail: None, hint: None, position: None, where_: None, schema:
None, table: None, column: None, datatype: None, constraint: None,
file: Some("parse_relation.c"), line: Some(423), routine:
Some("checkNameSpaceConflicts") }) }) })
Does anybody have any idea of what I am doing wrong?
This is a known issue with self-relations and we hope to fix it soon. If you want to track this bug, follow this github issue. Please feel free to add a comment to explain your use case/problem over there.
In the meantime, here are some workarounds that you can use:
Find count using nested read
You can use a nested read to return all the records in followers and following and find the length of those arrays to get the count. This seems like the most straightforward way, so long as you're okay with fetching all the followers/following records.
const user = await prisma.user.findUnique({
where: {
id: userId,
},
include: {
followers: true,
following: true,
},
});
let followerCount = user.followers.length;
let followingCount = user.following.length;
Find count using separate count queries.
Alternatively, you can use the count API to find followers and following counts for a certain user.
// number of followers for some user "x" = number of times x.id appaers in "following" relation of other users.
const followerCount = await prisma.user.count({
where: {
following: {
some: {
id: userId,
},
},
},
});
// number of users that user "x" is following = number of times x.id appaers in "followers" relation of other users.
const followingCount = await prisma.user.count({
where: {
followers: {
some: {
id: userId,
},
},
},
});
Change schema to use explicit many-to-many notation
If you're okay with slightly tweaking your schema, you can explicitly define the many-to-many relation table.
model Follows {
follower User #relation("follower", fields: [followerId], references: [id])
followerId String
following User #relation("following", fields: [followingId], references: [id])
followingId String
##id([followerId, followingId])
}
model User {
id String #id #default(cuid())
followers Follows[] #relation("follower")
following Follows[] #relation("following")
}
You should be able to run the count query without issues in this way.

Discord.js/Mongodb How to update all database values

I am currently creating an economy bot for Discord, and i have a problem i don't know how to solve:
All users have a salary, that will be set with a command. I want to create a command that can update all users account with the set salary amount.
Instead of having to ping a specific user, how could i make it that the command would update values of all found users in the MongoDB Database?
Here is current code:
const profileModel = require("../models/profileSchema");
module.exports = {
name: 'pay',
aliases: [],
permissions: ["ADMINISTRATOR"],
description: "pay users their salary",
async execute(message, args, cmd, client, discord, profileData) {
const amount = profileData.pay;
const target = message.mentions.users.first();
try{
await profileModel.findOneAndUpdate({
userID: target.id,
}, {
$inc: {
bank: amount,
},
}
);
return message.channel.send(`Users have been paid.`);
} catch(err) {
console.log(err);
}
},
};
As you can see, currently its waiting for the user to ping a user. But i would want it to just update all found users inside the Database without needing to specify who it is.
I would really appereciate help!
Mongo has the method updateMany, docs found here, which updates all documents if the query is set to an empty object. So, just try:
await profileModel.updateMany({}, {
$inc: {
bank: amount,
},
}
);

Meteor: Publish using users profile properties rather than ID

I'm currently creating an app that will be used by multiple companies.
Each user has the following profile:
username: johnDoe
emails: [{address: "some#email.com", verified: true}],
profile: {
name: "John Doe",
companyId: "1234"
}
I then have a collection (called Companies) of company objects that contain configuration info, templates etc specific to that company.
{
id: "1234",
configuration: {},
templates: []
}
In order to isolate each companies data I want to only publish data that matches the users profile companyId to the companies id.
if (Meteor.isServer) {
// collection to store all customer accounts
Companies = new Mongo.Collection('Companies');
// publish collection
Meteor.publish("Company", function () {
return Companies.find({id: Meteor.user().profile.companyId});
})
}
This currently works if I hardcode the clinic Id
// publish collection
Meteor.publish("Company", function () {
return Companies.find({id: "1234");
})
But returns an empty cursor with the Meteor.user().profile.companyId.
This means that the issue is either that I'm using the wrong function or more probably, the publish is happening before the user().profile.companyId can run.
Anybody know what I'm doing wrong? and do you have any advice on what to read up about so that I have an understanding of this moving forwards?
Thanks
Try doing an explicit findOne() in your publish function:
// publish collection
Meteor.publish("Company", function () {
var user = Meteor.users.findOne({_id: this.userId});
if(user && user.profile && user.profile.companyId) {
return Companies.find({id: user.profile.companyId});
} else {
console.log(user);
return this.ready();
}
});