I'm building a chatting system which consists of conversations which have participants and messages.
When the user opens the chat component I'm attempting to load the user's conversations by doing the following:
const conversations = await getConnection()
.getRepository(Conversation)
.createQueryBuilder('conversation')
.leftJoinAndSelect('conversation.participants', 'participant')
.where('participant.uuid = :participantUuid', { participantUuid })
.getMany()
This does return the conversations that the user is a participant in, but also filters out the participants in the conversation to return only the user assigned in the where clause. Is there a way to alter the query using the query builder to return the conversations the user is in but also all the participants of the conversations?
Related
I have a user model with two roles
Manager
Employee
Each manager has an manager idea that references the User model
I have a new model called Customers
The customers will either have user id of manager or employee
I want to create a controller to view the customers that are under the manager and the employees of that manager
let employees= await Employee.find({ managerId: req.user._id });
const customers= await Customer.find({
registeredBy: { $in: [employees._id] },
});
this is only returning the customers that are NOT registered by any employee or manager. What is the correct way to achieve this?
edit
This is how my customer collection looks like
_id:ObjectId('61e2a99752f9023ef0f9a1a6')
serialNo:"421A"
registeredBy:ObjectId('61d02ae060ccdd5a7a95813a')
If the manager is searching, the record of all the Customers having that manager id as registeredBy as well as the Customers having registerBy of the employees that have that *managerId in Employee schema should be shown
Whenever a user uses the Firebase Auth to register on my app, I create a document in a users collection of Firestore that stores metadata such as pseudo, userType, gender ...
To do that, the document id is exactly the same as the uid provided automatically by Firebase Auth (from the user UserRecord object)
Now, my app needs to fetch a user randomly from the users collection in Firestore.
I read Firestore: How to get random documents in a collection but this post suggest that I create the ID myself. The app is already built using the FirebaseAuth generated ID so what is the solution ?
A common practice in firestore is to create a "--Stats--" document within a collection (--Stats-- being the document id). This document can house information about the collection (number of documents, last updated, collection privileges etc.).
In your case, you could use cloud functions/triggers to keep tract of the total number of users in the users collection and add the id of a new user to a "userIds" array. You could keep both of these fields in the users collection's --Stats-- document. This way, when you wanted to get a random user, you could randomly generate a number betweeen 0 and the document count, then use it as an index of the userIds array. I might look something like this:
var usersCollectionRef= db.collection("users");
usersCollectionRef.doc("--Stats--").get().then((doc) => {
let numberOfUsers = doc.data().numberOfUsers;
let userIdArray = doc.data().userIds;
let randomNumber = Math.floor(Math.random() * (numberOfUsers + 1));
return usersCollectionRef.doc(userIdArray[randomNumber]).get();
}).then((doc) => {
...do something with the user's document
})
I'm currently using Stripe Webhooks to get notified when user pays for a product. This is working fine. From the payment intent I can get the Seesion and the Customer Object. But I don't find a way to get the product_id or price_id for what the user paid.
Does someone know a way to get product_id or price_id ?
Thanks for the question. As you noticed the Session data included in the checkout.session.completed event does not include the line_items where the Price ID is associated to the Checkout Session.
line_items is one of the expandable properties, so to retrieve the Price ID you'd retrieve the Checkout Session and use expand to include the line items in the response. There is not a way to configure your webhook to have the data sent to you include this data.
There are two approaches to associating a customer's purchase with a Checkout Session. First, you could store the ID of the Checkout Session in your database alongside the cart or list of items purchased by the customer. That way you if a checkout session is successful, you can look up the cart by ID and know which items were purchased.
Alternatively you could listen for the checkout.session.completed webhook event, then when you receive a new notification for a successful checkout, retrieve the Session with expand then use the related price data.
Using stripe-node that would look like the following:
const session = await stripe.checkout.sessions.retrieve(
'cs_test_xxx', {
expand: ['line_items'],
},
);
// note there may be more than one line item, but this is how you access the price ID.
console.log(session.line_items.data[0].price.id);
// the product ID is accessible on the Price object.
console.log(session.line_items.data[0].price.product);
To take this a step further, if you wanted more than just the ID of the product, you could also expand that by passing line_items.data.price.product which would include the line items their related prices and the full product objects for those prices.
While creating the Payment Intent, you can store additional information about the object in the metadata field.
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
payment_method_types: ['card'],
metadata: {
product_id: '123',
price_id: '20',
},
});
Once the payment is done, you can retrieve this information from the metadata field.
You can do the same for the Session Object as well.
cjav_dev answer is great! Here is the PHP code for the same.
$event = \Stripe\Event::constructFrom(
json_decode($payload, true), $sig_header, $endpoint_secret
);
$eventObject = $event->data->object;
$stripe = new StripeClient('testsk_ssdfd...sdfs');
$csr = $stripe->checkout->sessions->retrieve($eventObject->id,
['expand' => ['line_items']]
);
$priceid = $csr->line_items['data'][0]['price']['id'];
Note the above is only retrieving the 1st line item. You may have to do a loop for all items.
I have a channel(model Channel) belongsTo a owner(model User) and hasMany fans(model User), I can get current user id in a request and I want to get all the channels that
(channel.owner_id == current_user_id or count(channels.fans.id == current_user_id)) > 0
that is:
select all the channels that current user is the owner of the channel or is a fan of the channel
How can I combine the two requirement in one $or query using sequelize of Node.js?
Thanks a lot!
I've successfully retrieved a user's id and screen name from Twitter's oauth service, like so:
{ user_id: '12345678', screen_name: 'spencergardner' }
I am hoping to create a simple way for users to authenticate using Twitter (and soon Facebook, for example), so that they can add words they are interested in learning to their account. How do I now go about setting up "users" in a mongodb collection that will allow each user to have their own bank of words (and other data)?
If I understand you correctly, you are asking how you can store data with different structures in a mongo collection.
Well, you're in luck! Mongo does just that. You can store any different data structures in a mongo collection without having to "declare" the structure a priori. Just create a DBObject (if using the Java driver for example), add fields to it, and just save it. You can then retrieve it, and query the data to see what this specific users has, and anything you want in your application.
I use mongoose with nodejs to create a user model which you would then input the oauth data into and then you would be free to associate whatever data you wanted.
Once you've obtained the Oauth information you could create a new User associating the twitter data with that specific user model. The _id is automatically provided however in this case, you would use the user_id returned from twitter (assuming that is unique).
Here's an example schema:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var userSchema = new Schema({
_id: String,
screen_name: String,
words: Array
});
module.exports = mongoose.model('User', userSchema);
In future you would be able to query the database for a particular user, and authenticate a user when they return. You would also look to create a new User with something similar to the following:
new User({ _id: req.body.user_id,
password: req.body.screen_name,
words: []
}).save(function(err) {
if (!err) {
res.send("User added");
}
})