简体   繁体   中英

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;

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM