Oluwakorede Fashokun
Oluwakorede Fashokun

Reputation: 129

Mongoose not working with destructured imports

I have been working on a simple Express app with ES6. When creating a schema and model for Mongoose, I use this syntax:

import mongoose, { Schema } from 'mongoose';

const PostSchema = new Schema(
  {
    userId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    video: {
        type: String,
        required: true
    },
    location: {
        type: { type: String },
        coordinates: []
    }
  },
  { timestamps: true }
);

PostSchema.index({ location: '2dsphere' });

const Post = mongoose.model('Post', PostSchema);
export default Post;

It generates this error: TypeError: _mongoose.Schema is not a constructor.

When I use this syntax, it works:

import mongoose from 'mongoose';
const { Schema } = mongoose;
...

This is my .babelrc:

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

Is there anything wrong with my import style, or my Babel config? Thanks.

Upvotes: 1

Views: 372

Answers (1)

Aaron Adams
Aaron Adams

Reputation: 1665

Mongoose does not support destructuring imports.

https://mongoosejs.com/docs/faq.html#destructured-imports

The only import syntax Mongoose supports is import mongoose from 'mongoose'. Syntaxes like import * from 'mongoose' or import { model } from 'mongoose' do not work. The global Mongoose object stores types, global options, and other important properties that Mongoose needs. When you do import { model } from 'mongoose', the this value in model() is not the Mongoose global.

When using TypeScript you should be able to get away with destructuring interfaces and types, but that's about it.

Upvotes: 1

Related Questions