【问题标题】:Mongoose not working with destructured imports猫鼬不使用解构进口
【发布时间】:2019-03-20 02:19:36
【问题描述】:

我一直在使用 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 配置有什么问题吗? 谢谢。

【问题讨论】:

  • 我很确定导入语法没有解构。

标签: javascript express mongoose ecmascript-6


【解决方案1】:

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 时,您应该能够摆脱对接口和类型的解构,但仅此而已。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2017-11-19
    • 2016-12-26
    • 2017-01-08
    • 2016-01-10
    • 2020-10-29
    • 2018-04-24
    • 2022-06-13
    相关资源
    最近更新 更多