Search code examples
javascriptnode.jsmongodbpassport.jsbson

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


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?


Solution

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