Reputation: 129
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
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 likeimport * from 'mongoose'
orimport { model } from 'mongoose'
do not work. The global Mongoose object stores types, global options, and other important properties that Mongoose needs. When you doimport { model } from 'mongoose'
, thethis
value inmodel()
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