poldeeek
poldeeek

Reputation: 333

find object by id which is in array mongoose

My chat object has got an array with two elements - users id. I have first id from url params, but second id I have in array of users. Now I want to get all chats where first id is this one from url, and second is in the array. I think that example how I tried to do it will be the best explanation of this problem :

Chat.find({
        users: { $all: [req.params.id, { $in: usersIdArray }] }
    })

where usersIdArray is for example:

[ 5f8777a01d8c122e74cb6f08, 5f8777721d8c122e74cb6f02 ]

they are numbers, not strings. I don't know if it is important...

The error I get now :

(node:12168) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ '$in': [ 5f8777a01d8c122e74cb6f08, 5f8777721d8c122e74cb6f02 ] }" at path "users" for model "Chat"

And my chat schema:

    // 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 });

Upvotes: 2

Views: 314

Answers (2)

poldeeek
poldeeek

Reputation: 333

@Christian Fritz, I had to add $or to your solution and everything is fine now:

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

Upvotes: 0

Christian Fritz
Christian Fritz

Reputation: 21384

Since the length of your array is fixed (2), you can just query based on array position:

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

If that doesn't work then probably because usersIdArray are actually not ObjectIds, in which case you'd need to map them:

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

Upvotes: 2

Related Questions