Prisma splice Item from Array - prisma

I have been pushing updates to an array and was wondering if there is a built-in method to remove an entry from the array as well. Basically reversing the push command. I suspect that I have to query all documents and remove the item myself. But maybe there is some functionality I was unable to find inside the documentation.
Push:
const addTag = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
push: 'computing',
},
},
})
Remove Expectation:
const removeTag = await prisma.post.update({
where: {
id: 9,
},
data: {
tags: {
splice: 'computing',
},
},
})

As of writing, there's no method to splice/remove items from a scalar list using Prisma. You would have to fetch the scalar list from your database, modify it manually in your application code and overwrite the record in your database with an update operation.
There is a feature request for this, please feel free to follow/comment with your use-case to help us track demand for this feature.

const { dogs } = await prisma.user.findOne({
where: {
id: userId
},
select: {
dogs: true
},
});
await prisma.user.update({
where: {
id: userId
},
data: {
dogs: {
set: dogs.filter((id) => id !== 'corgi'),
},
},
});

Related

Reading an array into another array and storing all objects into a list using mongoose

I have a model (user) which contains an array (discontinued items). IDs are stored within this array, all of which belong to a specific item model. Now I would like to list all users where this array is not empty and then, in the same step, read out all articles from this array using their ID. Unfortunately, I can't do this because I get "undefinded" in the console when I print. What is that? Thank you very much
export const AlleUserMitArtikel = async (req, res) => {
try {
const alleUser = await User.find({
eingestellteArtikel: { $exists: true, $not: { $size: 0 } },
});
const liste = await Promise.all(
alleUser.map(async (user) => {
console.log(user); //Displays the correct object in the console, see below
user.eingestellteArtikel.map(async (id) => {
console.log(id); //Displays the correct ID, see Error section first two entries
return await Artikel.find({ _id: id });
});
})
);
console.log(liste); //Displays undefined
res.status(200).json(alleUser);
} catch (error) {
console.log(error);
}
};
USER MODEL:
{
_id: new ObjectId("630f36f0295ec768e2072c10"),
eingestellteArtikel: [ '630fe7caabfdf4387030a723', '63105cbedae68f22984ba434' ],
createdAt: 2022-08-31T10:24:48.845Z,
updatedAt: 2022-09-01T07:18:22.044Z,
__v: 0,
}
Undefined message:
630fe7caabfdf4387030a723
63105cbedae68f22984ba434
[ undefined, undefined ]

use where query depends on query on prisma

const fictions = await client.fiction.findMany({
where: {
AND: [
{ genre: genres as string },
{ nationality: nationalities as string },
{
keywords: {
some: {
keyword: {
name: keywords?.toString().split(",").join(" | "),
},
},
},
},
],
},
include: { ~~~
},
orderBy: {
userFictionStat: {
total: "asc",
},
},
});
Hi, I'm new to prisma so stuck in createing api pages.
I want to filter my 'fictions' with multiple criteria
('genre' or 'nationality' or 'keywords').
The problem is that when 'genre' or 'nationality' or 'keywords' are 'undefined'(button unclicked), the result becomes 0.(because of the 'AND').
I can't find out how can I filter my fictions with given criteria(with clicked buttons, even if some buttons are unclicked).
Also, I'd like to know how can I sort my fictions using my queries.
(lik if i get query {sorting : totalpoint} I can sory by totalPoint, and if i get {sorting : title} then I can sort by title name.
If anyone could help, I would be very thank you.
If genres can be undefined or false-y (including '' or "") then you can do typeof genres === "string" ? genres : undefined as part of your filter. Same for nationalities. That way you know you're passing a string which has meaningful content OR you are ignoring the filter.

Better way to perform this Relation "transaction" in Prisma

I posted a question yesterday that has the relevant prisma schema which can be found here.
As a follow up question, when a member creates a new Organization, I'd like for it to become their selected Membership. The only way I've found to do this is to deselect their current Memebership (set it to null), do the create, then restore the relationship if that create didn't work. I have to use updateMany for that initial operation in case there is no selectedMembership. Is that right?
//Deselect the currently selected Org
const updatedMembership = await prisma.membership.updateMany({
where: {
selectedById: user.id
},
data: {
selectedById: null
}
});
if (updatedMembership) {
//Select the new one.
const result = await prisma.organization.create({
data: {
name: body.name,
members: {
create: [{
role: MemberRole.OWNER,
userId: user.id,
selectedById: user.id
}]
}
},
});
if (result) {
res.status(200)
.json(result);
} else {
//Restore the previously selected one if the create failed
if(user.selectedMembership) {
await prisma.membership.update({
where: {
id: user.selectedMembership?.id
},
data: {
selectedById: user.id
}
});
}
res.status(500).end();
}
}
You can use the connect API to do all of this in a single query. Just make sure that the user.id is valid.
Here's a much cleaner version of the create and update query logic in your question:
const result = await prisma.organization.create({
data: {
name: body.name,
members: {
create: {
role: MemberRole.OWNER,
user: {
connect: {
id: user.id, // making the user a member of the organization
},
},
selectedBy: {
connect: {
id: user.id, // selecting the newly created membership as the user's default organization
},
},
},
},
},
});
This will handle all cases, regardless of whether the user with id = user.id currently:
Is a member of other organization(s) and has another membership as their default
Is a member of other organization(s) but has no default membership
Is not a member of any organization and has no default membership

Mongoose update the ENTIRE object inside a document with a nested array

There are so many questions and answers regarding this subject but why not make it simple.
Branch schema
const Branch = new Schema({
name: { Type: String },
address: {
houseNumber: { Type: String },
street: { Type: String },
city: { Type: String }
}
})
Client schema
const Client = new Schema({
...,
...,
branches: [ branch ] // BRANCH SCHEMA IS SUB DOCUMENTED HERE
})
I know how to $push and $pull branch from branches array.
What I need is to UPDATE the ENTIRE branch object inside branches array, NOT JUST ONE FIELD like I found in so many answers and YES I would like to have back the modified document.
let clientId = req.body.clientId;
let branch = req.body.branch;
Client
.findOneAndUpdate(
{
"_id": clientId,
"branches._id": branch._id
},
{
OPTION 1 // MODIFIED ONLY THE FIRST ITEM (object) IN THE ARRAY
"$set:" { "branches.$": { branch } }
OPTION 2 // MODIFIED EVERY ITEM (object) IN THE ARRAY
"$set:" { "branches.$[]": { branch } }
STILL NO GOOD... HOW TO SOLVE THIS ??
}
)
.then(client => {
WHAT SHOULD I DO HERE IN ORDER TO UPDATE AN ENTIRE BRANCH ??
})
.catch(e => console.log(`error Client.findOne() ${e}`))
You can use mongoose arrayFilters to achieve what you want:
Client
.findOneAndUpdate(
{
"_id": clientId,
"branches._id": branch._id
},
{
"$set:" { "branches.$[elem]": { branch } }
},
{
arrayFilters: [ { 'elem._id': branch._id } ]
}
)
.then(client => {
})
.catch(e => console.log('error Client.findOne() + e))
Okay, here is how I did it..
let clientId = req.body.clientId;
let branch = req.body.branch;
Client
.findOne({ _id: clientId })
.then(client => {
// finding the index
const elementIndex = client.branches.findIndex(element => element._id.toString() === branch._id.toString());
// creating new array and assigning the branches array to it using spread syntax
let newBranches = [ ...client.branches ];
// adding the branch I need to update to newBranches array (at the same index)
newBranches[elementIndex] = branch;
// replacing branches array with the new one, again using spread syntax
client.branches = [ ...newBranches ];
// saving
client.save();
})
.catch(e => console.log(`error Client.findOne() ${e}`))
enjoy!

Why I'm I getting an error saving date using graphql > hasura > postgres

I'm using react, apollo, graphql, hasura, postgres as my stack to interact with the database. I think my issue is something small, so I'll just focus on the part that's not working rather than posting the whole code.
Thanks.
Error: GraphQL error: unexpected variables in variableValues: birthday
at new ApolloError (bundle.esm.js:63)
at Object.next (bundle.esm.js:1004)
at notifySubscription (Observable.js:135)
at onNotify (Observable.js:179)
at SubscriptionObserver.next (Observable.js:235)
at bundle.esm.js:866
at Set.forEach (<anonymous>)
at Object.next (bundle.esm.js:866)
at notifySubscription (Observable.js:135)
at onNotify (Observable.js:179)
at SubscriptionObserver.next (Observable.js:235)
at bundle.esm.js:76
variables{ id: 2324324, name: "Fred", birthday: "1991-01-11" }
If i remove birthday the query works.
Here is the function
const onUpdateUser = (options) => {
updateUser({
variables: Object.assign({ id: userId }, options),
optimisticResponse: {
__typename: "mutation_root",
update_users: {
__typename: "users_mutation_response",
affected_rows: 1,
returning: [
{
__typename: "users",
id: userId,
...options,
},
],
},
},
});
};
input {birthday: '1991-01-11'}
So without looking at your graphql query, I think you may be thinking of it a little bit off.
You can't dynamically add non-existent variables to a graphql query. The error is telling you that you are trying to add a variable that doesn't exist in your query
i.e. this with NOT work because you haven't defined birthday.
mutation updateUser(
$userId: Int!
$birthday (UNDEFINED)
) {
rest of query...
}
If you need to add a dynamic amount of variables, you could do something like this.
React Code
const onUpdateUser = (options) => {
updateUser({
variables: {
userId,
userVariables: options
},
optimisticResponse: {
__typename: "mutation_root",
update_users: {
__typename: "users_mutation_response",
affected_rows: 1,
returning: [
{
__typename: "users",
id: userId,
...options,
},
],
},
},
});
};
GraphQL mutation
mutation updateUser(
$userId: Int!
$userVariables: user_set_input!
) {
update_user(
where: { id: { _eq: $userId} }
_set: $userVariables
) {
affected_rows
}
}
https://hasura.io/docs/1.0/graphql/manual/mutations/update.html