Making duel queries in prisma client - javascript

I'm currently wondering if its possible to get data from more than one table in a single query?
We have a teamMember table, and a user table. We want to fetch information on each user in the teamMember table, and get the corresponding data from the user table.
Is this possible to do in one query? Or would I have to use two findMany queries?
const members = await prisma.teamMember.findMany({
where: {
teamId,
},
});
const membersInfo = [];
members.map(async (e) => {
const response = await prisma.user.findFirst({
where: {
id: e.userId,
},
});
if(response) membersInfo.push(response);
});```

Yes, you could query User data while fetching TeamMember information.
Consider this example:
schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model TeamMember {
id Int #id #default(autoincrement())
team_id Int
User User? #relation(fields: [userId], references: [id])
userId Int?
}
model User {
id Int #id #default(autoincrement())
name String
email String
password String
team TeamMember[]
}
index.ts
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
log: ['query'],
});
async function main() {
await prisma.user.create({
data: {
email: 'test#test.com',
name: 'test',
password: 'test',
team: {
create: {
team_id: 1,
},
},
},
});
console.log('Created user');
const teamWithUsers = await prisma.teamMember.findUnique({
where: {
id: 1,
},
include: {
User: true,
},
});
console.log('teamWithUsers', teamWithUsers);
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
Here's the response:
teamWithUsers {
id: 1,
team_id: 1,
userId: 1,
User: { id: 1, name: 'test', email: 'test#test.com', password: 'test' }
}
By default relation fields are not fetched, if you need to get the relation fields data in that case you would need to specify the include clause as demonstrated in the above example.

Related

How to retreive an object from an array of Objects in mongodb given a objectid

I have an array of reviews, I want to retrieve only a review from an array of objects inside a schema.
Here is my schema:
const sellerSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
reviews: [
{
by: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
title: {
type: String,
},
message: {
type: String,
},
rating: Number,
imagesUri: [{ String }],
timestamp: {
type: Date,
default: Date.now,
},
},
],
});
How can I get a single review from the array if 'by' will be req.user._id. I have the previous code, but it is not working to retrieve the review only that satisfies the query.
try {
const seller_id = mongoose.Types.ObjectId(req.params._id);
const review = await Seller.findOne(
{ _id: seller_id },
{ reviews: { $elemMatch: { by: req.user._id } } } //get the review that matches to the user_id
);
res.status(200).send(review);
} catch (err) {
//sends the status code with error code message to the user
res.status(502).send({
error: "Error retreiving review.",
});
}
This retrieves the whole seller document, but I just want to retrieve the object review with the given a user_id === by: ObjectID
give it a try
try {
const seller_id = mongoose.Types.ObjectId(req.params._id);
const review = await Seller.findOne(
{ _id: seller_id , "reviews.by": req.user._id}, { "reviews.$": 1 }
);
res.status(200).send(review);
}
Try to cast also the user _id as ObjectId and unify your conditions into a single object:
try {
const seller_id = mongoose.Types.ObjectId(req.params._id);
const user_id = mongoose.Types.ObjectId(req.user._id);
const review = await Seller.findOne({
_id: seller_id,
reviews: { $elemMatch: { by: user_id } },
});
res.status(200).send(review);
} catch (err) {
//sends the status code with error code message to the user
res.status(502).send({
error: 'Error retreiving review.',
});
}

Can't pass multiple documents in an array when using findById

I want to find each of the elements in the array by their id and send it with the post request to create a new post. Right now when I create a new post only passes the first index of the array and if I use find() it passes all of the social schemas regardless if it is in the body of the request. I hope this makes sense if it doesn't please let me know. I hope someone can help.
Below is the mongoose schema for the qrcode post also using Joi
const Joi = require("joi");
const mongoose = require("mongoose");
const { themeSchema } = require("./Theme");
const { userSchema } = require("./User");
const { socialSchema } = require("./Social");
const QrCode = mongoose.model(
"QrCode",
new mongoose.Schema({
user: {
type: userSchema,
required: true,
},
name: {
type: String,
maxLength: 255,
required: true,
trim: true,
},
theme: {
type: themeSchema,
required: true,
},
// Social Media Links
social: [
{
type: socialSchema,
required: true,
},
],
})
);
function ValidateQrCode(qrCode) {
const schema = {
userId: Joi.objectId(),
name: Joi.string().max(255).required(),
themeId: Joi.objectId().required(),
socialId: Joi.array().required(),
};
return Joi.validate(qrCode, schema);
}
module.exports.QrCode = QrCode;
module.exports.validate = ValidateQrCode;
this is the post route to create a new qrcode
router.post("/", auth, async (req, res) => {
const { error } = validate(req.body);
if (error) res.status(400).send(error.details[0].message);
const theme = await Theme.findById(req.body.themeId);
if (!theme) return res.status(400).send("Invalid theme.");
const user = await User.findById(req.user._id);
if (!user) return res.status(400).send("Invalid theme.");
const social = await Social.findById(req.body.socialId);
if (!social) return res.status(400).send("Invalid social.");
const qrCode = new QrCode({
user: user,
name: req.body.name,
theme: theme,
social: social,
});
await qrCode.save();
res.send(qrCode);
});
In the body of my Postman request I am inputting the info below
{
"name": "Friends",
"themeId": "60f89e0c659ff827ddcce384",
"socialId": [
"60f89e43659ff827ddcce386",
"60f89e5c659ff827ddcce388"
]
}
To fetch data using ids, you can use below mongodb query simply,
db.collection.find( { _id : { $in : ["1", "2"] } } );
In mongoose,
model.find({
'_id': { $in: [
mongoose.Types.ObjectId('1'),
mongoose.Types.ObjectId('2'),
mongoose.Types.ObjectId('3')
]}
}, function(err, docs){
console.log(docs);
});
Or
await Model.find({ '_id': { $in: ids } });

User data not returning anything from query call

I'm not sure which part I might be doing wrong. I was hoping to get some advice.
The query I am using in GraphiQL is:
query getUser($id:Int!) {
user(id:$id) {
id
email
}
}
For the backend I am using NodeJS. I am also declaring the user type as:
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLID },
email: { type: GraphQLString }
})
});
My root query is:
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: { id: { type: GraphQLInt } },
resolve(parentValue, args) {
const query = `SELECT * FROM users WHERE id=$1`;
const values = [ args.id ];
dbQuery.query(query, values).then(({ rows }) => {
console.log(rows[0]);
return rows[0];
});
}
}
}
});
const schema = new GraphQLSchema({ query: RootQuery });
app.use(
'/api/v1/graphql',
graphqlHTTP({
schema: schema,
graphiql: true
})
);
What I get in return is:
{
"data": {
"user": null
}
}
I was hoping to know what I might be doing wrong that is resulting in null being returned instead of the data that I am querying from the database.
Thank you for all the help.
It will be much more clear if you use with await
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: { id: { type: GraphQLInt } },
resolve: async(parentValue, args) {
const query = `SELECT * FROM users WHERE id=$1`;
const values = [ args.id ];
const rows = await dbQuery.query(query, values);
return rows[0];
}
}
}
});
When using a promise and returning anything inside the promise will only return the result to the promise that is executed. It will not be returning as a whole to the parent function.
You can also return the whole promise function like below
return dbQuery.query(query, values)

Mongoose - Model.deleteOne() is deleting the entire collection instead of a single document

I have a User model that contains an array of customers. I want to delete a specific customer based on the customer _id. From what I've read in the Mongoose docs, I should use Model.deleteOne to delete a single document.
Here is my attempt
User Schema (it's been shortened for brevity):
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
username: {
type: String,
default: ''
},
password: {
type: String,
default: '',
},
registerDate: {
type: Date,
default: Date.now()
},
customer: [{
name: {
type: String,
default: '',
},
email: {
type: String,
default: 'No email name found'
},
fleet: [{
unitNumber: {
type: String,
default: 'N/A',
}
}]
}]
});
module.exports = mongoose.model('User', UserSchema);
Here is a look at the route and controller:
const express = require('express');
const router = express.Router();
const customer_controller = require('../../controllers/customers');
router.delete('/customers/:custid', customer_controller.customer_remove);
module.exports = router;
And finally the controller:
exports.customer_remove = (req, res) => {
const { params } = req;
const { custid } = params;
User.deleteOne({ 'customer._id': custid }, (err) => {
if (err)
throw err;
else
console.log(custid, 'is deleted');
});
};
From what I thought, User.deleteOne({ 'customer.id': custid }) would find the customer _id matching the custid that is passed in via the req.params. When I test this route in Postman, it deletes the entire User collection that the customer is found in, instead of just deleting the customer. Can I get a nudge in the right direction? I feel like I am close here (or not lol).
deleteOne operates at the document level, so your code will delete the first User document that contains a customer element with a matching _id.
Instead, you want update the user document(s) to remove a specific element from the customer array field using $pull. To remove the customer from all users:
User.updateMany({}, { $pull: { customer: { _id: custid } } }, (err) => { ...
Using Mongoose you can do this:
model.findOneAndUpdate({ 'customer._id': custid }, {$pull: { $pull: {
customer: { _id: custid } }}, {new: true}).lean();
Removing subdocs.
Each sub document has an _id by default. Mongoose document arrays have a special id method for searching a document array to find a document with a given _id.
Visit: https://mongoosejs.com/docs/subdocs.html
parent.children.id(_id).remove();
Use async-await, may be that will work.
exports.customer_remove = async (req, res) => {
const { params } = req;
const { custid } = params;
try {
await User.deleteOne({ 'customer._id': custid });
console.log(custid, 'is deleted');
} catch (err) {
throw err;
}
};

Unable to retrieve user id when creating a new account

I do not know why I unable to retrieve user id when creating a new account and add a role for this user.
methods.js :methods for update and insert new account driver with which I would assign the roles 'driver' for every new account ,registering a new account is going successfully, but the addition of a role does not work
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { CONST } from '../../common/constants.js';
import { Roles } from 'meteor/alanning:roles';
Meteor.methods({
updateUserProfile: (newProfile) => {
const userId = Meteor.userId();
// var isEmailChanged = currentProfile ?
// newProfile.email != currentProfile.email :
Meteor.users.update(userId, {
$set: {
profile: newProfile,
},
}, {
validationContext: 'updateUserProfile',
});
},
createDriver: (newUser) => {
var id =Accounts.createUser({
username: newUser.username,
email: newUser.email,
password: newUser.password,
profile: newUser.profile,
roles: CONST.USER_ROLES.DRIVER,
});
//console.log(Meteor.userId());
Roles.addUsersToRoles(id, roles);
},
});
Driver-join.js
Meteor.call('createDriver', data, (error) => {
if (error) {
Session.set(SESSION.ERROR, error);
} else {
FlowRouter.go('/s/driver/vehicles'); // TODO : replace with redirection by root name
}
});
roles
roles: {
type: [String],
optional: true,
allowedValues: [CONST.USER_ROLES.CLIENT, CONST.USER_ROLES.DRIVER, CONST.USER_ROLES.ADMIN],
defaultValue: CONST.USER_ROLES.CLIENT,
},
What if add this to the server?
Meteor.users.after.insert(function (userId, doc) {
Roles.addUsersToRoles(doc._id, [CONST.USER_ROLES.DRIVER])
});
Also remove roles property when you add new user, it doesn't work.
But your code should work as well. What is the roles in Roles.addUsersToRoles(id, roles);?

Categories

Resources