通过id在数组猫鼬中找到对象

时间:2020-10-18 23:47:36

标签: node.js mongodb mongoose

我的聊天对象有一个包含两个元素的数组-用户ID。我有url参数中的第一个ID,但是我在用户数组中有第二个ID。现在,我想获取所有聊天,其中第一个id是url中的一个,第二个id是数组中的。我认为该示例将是我对问题的最佳解释:

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 个答案:

答案 0 :(得分:2)

由于数组的长度是固定的(2),因此您可以query based on array position

Chat.find({
  "users.0": req.params.id,
  "users.1": {$in: usersIdArray}
});

如果这不起作用,则可能是因为usersIdArray实际上不是ObjectId,在这种情况下,您需要映射它们:

usersIdArray.map(x => ObjectId(x))

答案 1 :(得分:0)

@Christian Fritz,我必须在您的解决方案中添加$ or,现在一切都很好:

create-react-app