Skip to content
Advertisement

get message between two user

i want to retrieve conversation between two user sorting by the newest with the user sender field my message and user schema :

const messageSchema = new mongoose.Schema({
from:{
    type: mongoose.Schema.Types.ObjectId,
    ref:'User'
},
to:{ 
    type: mongoose.Schema.Types.ObjectId,
    ref:'User'},
date:{
    type:String, default:new Date()
},
message: {type:String},
seen:{type:Boolean,default:false}

},{timestamps:true})

const userSchema = new mongoose.Schema({
    name : {
        type: String,
        required: true,
    },

lastname : {
    type: String,
    required: true,
},
firstname : {
    type: String,
    required: true,
    },
})

Advertisement

Answer

i found a solution :

const conversation = await Message.find({$or: [
    {'from': req.user._id,'to': userId},
    {'from':userId,'to':  req.user._id}
]},
).populate('from','name image ').limit(20);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement