How to get object type after retrieving it as document from mongodb?

Viewed 136

I am developing a nodejs app with multiple kinds of users, for example "user" and "page". I am using MongoDB to save my data, and passportjs for authentication. I need to provide different serialization methods according to user type. Sample code:


    passport.serializeUser((obj, done) => {
        if (obj instanceof User) {
            console.log("serialising user", obj);
            done(null, { id: obj._id, type: 'user' });
        } else if (obj instanceof Page) {
            console.log("serialising page", obj);
            done(null, { id: obj._id, type: 'page' });
        } 
    });

The problem here is that instanceof does not work with documents retrieved from MongoDB. They were created using the constructors of User/Page, but now I can't differentiate between them, since they are now both of type object. How should I deal with this?

2 Answers

find a unique field from these two different collections and based on the field and field value apply this logic

What I ended up doing is indeed using a field obj.userType ='user'/'page' in the returned objects, but it I did not save it in the database. Instead I query the object, get the document BSON back, and then simply add the field to it. This way I don't have to save it to all users all of the times, it's just their for the retrieved user object needed for the session until it terminates.

Related