I am doing project with React Typescript Next and prisma, I am trying to create user with initally empty array as playlists field, I dont get any error but when i refresh my database (mongodb) i cannot see playlists prop on my newly created user. Firstly I thought that if that is empty I just cant see it, but then when i wanted to invoke to it and update this field, I realized that it is not possible.
My schema.prisma file:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
email String @unique
emailVerified DateTime
image String?
hashedPassword String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
playlists Playlist[]
recentSearches Json[]
liked Json
}
model Playlist {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
tracks Json[]
image String?
isPublic Boolean @default(true)
author String?
User User @relation(fields: [userId], references: [id])
userId String @db.ObjectId
}
My register user logic:
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "POST") {
return res.status(405).end();
}
try {
const { email, name, password } = req.body;
const existingUser = await prismadb.user.findUnique({ where: { email } });
if (existingUser) {
return res
.status(422)
.json({ error: "Email is already taken", cause: "email" });
}
const hashedPassword = await bcrypt.hash(password, 12);
const user = await prismadb.user.create({
data: {
email,
name,
hashedPassword,
image: "",
emailVerified: new Date(),
recentSearches: [],
liked: {},
playlists: { create: [] },
},
});
return res.status(200).json(user);
} catch (error) {
console.log(error);
return res.status(400).json(error);
}
}
I tried using create and createMany attribute but nothing worked, I realized that if i use Json[] instead of Playlist[] it works but i want to have Playlists[] as a type.
I expect to create a user with empty array of playlists field in database.
The way i want then update my playlists field
const createdPlaylist = await prismadb.playlist.create({
data: { name: playlistName, tracks: [], userId: user.id },
});
const result = await prismadb.user.update({
where: { id: user.id },
data: { playlists: { connect: { id: createdPlaylist.id } } },
});
2
Answers
I solved this issue, everything was working as expected but I just forgot to write {include: {playlists: true}} on object in find method so I didint see playlists in console.
In MongoDB, the behaviour for fields that are initially empty or not set explicitly is different from traditional SQL databases. In MongoDB, fields that are not set in a document are not stored in the database. This is different from SQL databases where all columns are present in every row, and empty fields are explicitly represented.
In your Prisma schema, the
playlists
field is defined as an empty array by default:When you create a new user using Prisma and MongoDB, the
playlists
field will not be stored in the database if it’s empty because MongoDB doesn’t store fields with empty arrays by default.If you want to ensure that the
playlists
field is always present in the user document, even if it’s initially empty, you can modify your schema to set a default value explicitly for that field:After making this change, you may need to regenerate your Prisma client to apply the updated schema: