mongoosemongodb-querynext.js13objectid

How to perform find operation for query with ObjectId in mongodb?


I have a database of sessions where I stored the active sessions of users. this is a screenshot of the Session database:

enter image description here

now, as we can see the user_id is storing the ObjectId of users and I want to find all active sessions for a specific user with below operation:

const findSessions = await Session.find({ user_id: existingUser._id });

But the problem is, for some reason, mongodb is treating the ObjectId as a plain string and returning empty array as result.

I've tried to convert it as ObjectId using below approach:

const userId = new mongoose.Types.ObjectId(existingUser._id);

but it says:

The signature '(inputId: number): ObjectId' of 'mongoose.Types.ObjectId' is deprecated.ts(6387) bson.d.ts(1239, 8): The declaration was marked as deprecated here. constructor Types.ObjectId(inputId: number): mongoose.Types.ObjectId (+6 overloads) Create ObjectId from a number.

@param inputId — A number.

@deprecated — Instead, use static createFromTime() to set a numeric value for the new ObjectId.


Solution

  • I suspect you need to upgrade your version of mongoose but for anyone running into the same problem the mongoose.Types.ObjectId is the ObjectId type.

    Therefore to create an instance of an ObjectId from a String you have two options:

    1. Use the ObjectId constructor and pass a 24 character hex String:
    const findSessions = await Session.find({ 
       user_id: new mongoose.Types.ObjectId(existingUser._id) 
    });
    
    1. Use the ObjectId.createFromHexString method and and pass a 24 character hex String:
    const findSessions = await Session.find({ 
       user_id: mongoose.Types.ObjectId.createFromHexString(existingUser._id) 
    });