我正在使用 mongoose 和 nestjs 構建一個聊天應用程式。這是我第一次嘗試使用 mongo 作為資料庫,所以我無法區分我應該使用哪個 mongo 查詢。
以下功能是查找登錄用戶和其他用戶之間的一對一聊天。我在 Insomnia 中測驗了這兩種方法,它們得到了相同的結果。
方法一
async findOneOnOneChat(currentUserId, userId) {
const oneOnOneChat = await this.chatModel
.find({
isGroupChat: false,
})
.and([
{ users: { $elemMatch: { $eq: currentUserId } } },
{ users: { $elemMatch: { $eq: userId } } }
])
return oneOnOneChat;
}
方法二
async findOneOnOneChat(currentUserId, userId) {
const oneOnOneChat = await this.chatModel
.find({
isGroupChat: false,
})
.and([{ users: { $in: userId } }, { users: { $in: id } }])
return oneOnOneChat;
}
所以我的問題是兩種方法有什么區別?哪種方法更好?或者有沒有更好的版本可以實作我想要的?
uj5u.com熱心網友回復:
這些是不同的事情。
使用{users: { $in: userId } }whenuserId是一個陣列,并且您希望user值匹配userId. 在這種情況下user,可以是單個值或值陣列,但userId必須是陣列。你可以把它想象成一個回圈userId,即為每個元素userId在user.
使用{ users: { $elemMatch: { $eq: userId } } }whereusers是一個陣列并且userId是單個值。你可以把它想象成一個回圈users,即為每個元素users尋找一個等于的匹配項userId。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465386.html
上一篇:快速獲取單個檔案不跳轉捕獲
