Search code examples
javascriptnode.jsmongoosees6-modulesmongoose-plugins

How to import mongoose-long plugin with es6 way


I want to convert following import syntax into es6 import syntax

const mongoose = require('mongoose')
require('mongoose-long')(mongoose);
const {Types: {Long}} = mongoose;

Solution

  • I don't normally use the ES6 syntax for modules so I consulted this article which seemed to be correct: https://codeburst.io/understanding-es6-modules-import-export-syntax-in-javascript-6c01f20cead3

    For your example this appeared to work for me (in my debugger I see the variable Long get a value and I can use it to create a Long value)

    import mongoose from 'mongoose'
    import mongooseLong from 'mongoose-long'
    mongooseLong(mongoose)
    const {Types: {Long}} = mongoose;
    const myVal = new Long(0, 0xffff)
    console.log(myVal)
    

    The only tricky step was handling require('mongoose-long')(mongoose). I introduced the variable mongooseLong to work around that one liner.

    For this to be executable I needed to add the following to my package.json (this is mentioned in the linked article):

    "type": "module"
    

    When I run this program I see the following

    > node index.js 
    Long { _bsontype: 'Long', low_: 0, high_: 65535 }