Reputation: 11
I am creating a messaging app and I need to be able to display the users with which a given user has conversation history. I have users and conversations. The models are below. (There is a messages collection where each document refers to a conversation)
//This is the conversation model.
const mongoose = require('mongoose');
const ConversationSchema = new mongoose.Schema({
participants: {
type: Array,
required: true
}
});
const Conversation = mongoose.model('Conversation', ConversationSchema);
//This is the users model (there's more to it, but this is the relevant stuff)
module.exports = Conversation;
const UserSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
Each has an _id that is generated. I am sending an http request with a user ID. In my controller, using mongoose, I am able to do the following:
Conversation.find({participants:req.params.user_id})
This returns an array of conversation objects, each of which contains a participants array(an array of user IDs). What I then need to do is match all the participants to the "users" collection so I can get the user ID, first name and last name of each user.
In summary, I need to send an HTTP request with a user ID as a parameter and receive an array of users which have conversation history with the provided user.
What is the next step? How can I match the user IDs I get from the relevant conversations to the user IDs in the users collection?
Upvotes: 0
Views: 32
Reputation: 409
Try with this
app.post('/:user_id', async(req, res) => {
const partisipant = await Conversation.find({id:req.params.user_id});
const userData = await User.find({id:req.params.user_id});
if(!userData || userData != partisipant){
throw ('no data match')
}
//...if found the data, do anything you want
})
Using async await to get collection data from database, and compare them.
Hope this clue can help you
Upvotes: 0