[英]MongoDB, Mongoose find all where _id is equal to key of object in array
[英]find object by id which is in array mongoose
我的聊天對象有一個包含兩個元素的數組 - 用戶 ID。 我有來自 url 參數的第一個 id,但我在用戶數組中有第二個 id。 現在我想獲取所有聊天,其中第一個 id 是來自 url 的,第二個在數組中。 我認為我嘗試做的那個例子將是對這個問題的最好解釋:
Chat.find({
users: { $all: [req.params.id, { $in: usersIdArray }] }
})
其中 usersIdArray 是例如:
[ 5f8777a01d8c122e74cb6f08, 5f8777721d8c122e74cb6f02 ]
它們是數字,而不是字符串。 不知道重要不重要...
我現在得到的錯誤:
(node:12168) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ '$in': [ 5f8777a01d8c122e74cb6f08, 5f8777721d8c122e74cb6f02 ] }" at path "users" for model "Chat"
還有我的聊天模式:
// Create schema
const ChatSchema = new Schema({
users: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Users',
}, {
type: Schema.Types.ObjectId,
ref: 'Users',
}],
required: [true, 'Podaj uczestników czatu.'],
},
lastMessage: {
type: Schema.Types.ObjectId,
ref: 'Message'
}
}, { timestamps: opts });
由於數組的長度是固定的(2),因此您可以根據數組位置進行查詢:
Chat.find({
"users.0": req.params.id,
"users.1": {$in: usersIdArray}
});
如果這不起作用,那么可能是因為usersIdArray
實際上不是 ObjectIds,在這種情況下,您需要映射它們:
usersIdArray.map(x => ObjectId(x))
@Christian Fritz,我不得不將 $or 添加到您的解決方案中,現在一切都很好:
Chat.find({
$or: [
{
"users.1": req.params.id,
"users.0": { $in: usersIdArray }
}, {
"users.0": req.params.id,
"users.1": { $in: usersIdArray }
}]
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.