how to write a mongoose query similar to "SELECT * FROM chats WHERE sender_id = 1 AND receiver _id = 2 OR sender_id = 2 AND receiver _id = 1"

Viewed 47

I want to show this data

[
  { chattext : 'hi', sender_id : 1, receiver_id : 2 }
  { chattext : 'hello', sender_id : 2, receiver_id : 1 }
  { chattext : 'how are you?', sender_id : 1, receiver_id : 2 }
]

how to write the mongoose query for the collections below?

const chatSchema = new mongoose.Schema({
  chattext : String,
  sender_id : Number,
  receiver_id : Number,
})

So, the result will be like

user1 : "hi"
user2 : "hello"
user1 : "how are you?"
2 Answers
var arr =await Chat.find();
arr.map((ar)=>{
console.log("user"+ar.sender_id+' : "'+ar.chattext'"');
}

keep in mind you need to

 const Chat = require("../Models/yourChatmodel");

This is the solution i got

I've got the answer bro! Luckyly i got the logic from someone who has asking about a OR b AND b OR a

const chats = Chat.find({
  $or : [
    { $and : [{ sender : 1 }, { receiver : 2 }] },
    { $and : [{ sender : 2 }, { receiver : 1 }] },
  ]
}
Related