Search code examples
node.jsmongodbmongooseschemapriority-queue

Why can't I store a PriorityQueue into MongoDB


Recently I have decided to replace arrays with priority queues for storing my list of jobs for a user into MongoDB. I use NodeJS and ExpressJS for backend. The priority queue I attempted to store is from an external package which can be installed by running the following command in terminal:

yarn add js-priority-queue

For some reason the priority queue works perfectly prior to storing it into MongoDB. However, the next time I attempt to take it out of MongoDB and use it, its functionality is missing. I declare its type as Schema.Types.Mixed in the Schema. Am I doing something wrong or is it not possible to store instantiated class objects into MongoDB?


Solution

  • As far as I know, when you store things in MongoDB they are stored as extended JSON (EJSON) in binary format (BSON)

        const { EJSON } = require('bson');    
        const test = EJSON.stringify({a: new Date(), foo:function(){console.log('foo');}})
        console.log(test) // "{"a":{"$date":"2020-07-07T14:45:49.475Z"}}"
    

    So any sort of function is lost.