首页 > 解决方案 > 通过数组 mongoose 中的 id 查找对象

问题描述

我的聊天对象有一个包含两个元素的数组 - 用户 ID。我有来自 url 参数的第一个 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 });

标签: node.jsmongodbmongoose

解决方案


由于数组的长度是固定的 (2),因此您可以根据数组位置进行查询

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

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

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

推荐阅读