Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 按数组mongoose中的id查找对象_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 按数组mongoose中的id查找对象

Node.js 按数组mongoose中的id查找对象,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我的聊天对象有一个包含两个元素的数组-users id。我有来自url参数的第一个id,但在用户数组中有第二个id。现在我想获取所有聊天记录,其中第一个id是来自url的,第二个是数组中的。我认为我如何尝试这样做的例子将是对这个问题的最好解释: Chat.find({ users: { $all: [req.params.id, { $in: usersIdArray }] } }) 其中usersIdArray是示例: [ 5f8777a01d8c122e74cb6f

我的聊天对象有一个包含两个元素的数组-users 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),因此您可以:

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

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 }
        }]
})

在我的情况下,这并不总是有效的。我不知道
req.params.id
中的id何时具有索引0或1。此数组中的ID按随机顺序排列,这取决于接受朋友邀请的人….:/
Chat.find({
    $or: [
        {
            "users.1": req.params.id,
            "users.0": { $in: usersIdArray }
        }, {
            "users.0": req.params.id,
            "users.1": { $in: usersIdArray }
        }]
})