繁体   English   中英

猫鼬不适用于解构的进口

[英]Mongoose not working with destructured imports

我一直在使用 ES6 开发一个简单的 Express 应用程序。 为 Mongoose 创建模式和模型时,我使用以下语法:

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;

它生成此错误: TypeError: _mongoose.Schema is not a constructor

当我使用此语法时,它可以工作:

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

这是我的.babelrc

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

我的导入样式或 Babel 配置有什么问题吗? 谢谢。

Mongoose 不支持解构导入。

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

Mongoose 支持的唯一导入语法是import mongoose from 'mongoose' 像语法import * from 'mongoose'import { model } from 'mongoose'工作。 全局 Mongoose 对象存储 Mongoose 需要的类型、全局选项和其他重要属性。 当您import { model } from 'mongoose'model()this值不是 Mongoose 全局值。

使用 TypeScript 时,您应该能够避免解构接口和类型,但仅此而已。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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