我正在與私人房間建立聊天。我想做的是找到一個兩個用戶也屬于的房間。如果沒有,則創建一個。
聊天模式
export const ChatSchema = new mongoose.Schema({
participants: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}],
created_at: { type: Date, default: Date.now },
});
詢問
async findChatBetweenUsers(participantOneId, participantTwoId) {
return await (await this.chatModel.findOne( { participants: [participantOneId, participantTwoId] } )).populate('participants');
}
控制器
async onJoinRoom(socket: Socket, reciever) {
const authUser: User = await this.authUser(socket);
const recievingUser: User = await this.userService.findOne(reciever.username);
const chat = await this.chatService.findChatBetweenUsers(authUser, recievingUser);
//Create new chat if doesn't exist
if(Object.entries(chat).length === 0){
const newChat = await this.chatService.create(authUser, recievingUser);
return;
}
console.log(chat)
}
我遇到的問題
和的順序會根據登錄用戶的不同auth而receiver變化,并為聊天生成不同的查詢結果。例如:
示例一
const chat = await this.chatService.findChatBetweenUsers('KylesId', 'ChrisId');
輸出
"chat" : {
"_id": 'chatOneId',
"participants": ['KylesId', 'ChrisId']
}
示例二
const chat = await this.chatService.findChatBetweenUsers('ChrisId','KylesId');
輸出
"chat" : {
"_id": 'chatTwoId',
"participants": ['ChrisId', 'KylesId']
}
盡管查詢的順序如何,我如何獲得相同的結果participants?
uj5u.com熱心網友回復:
相反,如果您希望找到一個包含元素“red”和“blank”的陣列,而不考慮陣列中的順序或其他元素,請使用 $all 運算子:
this.chatModel.find({
participants: {$all: [ObjectId('61ce732e33c7e8a9ad80e151'), ObjectId('61ccf3251b9ba5c8a6ecf2a3')]}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410947.html
標籤:
上一篇:通過貓鼬中的函式進行嵌套資料收集
下一篇:如何在貓鼬中填充物件陣列
