mongoose TypeError:Schema不是构造函数

Dav*_*røm 14 javascript mongoose node.js mongoose-schema

我遇到了一件奇怪的事.我有几个猫鼬模型 - 在其中一个(只有一个!)我得到这个错误:

TypeError: Schema is not a constructor
Run Code Online (Sandbox Code Playgroud)

我觉得很奇怪,因为我有几个工作模式.我尝试登录mongoose.Schema非工作模式,它确实与我工作模式中的mongoose.Schema不同 - 这怎么可能?代码几乎相同.这是非工作模式的代码:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var errSchema = new Schema({
  name: String,
  images:[{
    type:String
  }],
  sizes:[{
    type: String
  }],
  colors:[{
    type: Schema.ObjectId,
    ref: 'Color'
  }],
  frontColors:[{
    type: Schema.ObjectId,
    ref: 'Color'
  }],
  script: Boolean
},{
  timestamps: true
});

var Err = mongoose.model('Err', errSchema);

module.exports = Err;
Run Code Online (Sandbox Code Playgroud)

工作架构的代码:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var colorSchema = new Schema({
  name: String,
  image: String,
  rgb: String,
  comment: String,
});

var Color = mongoose.model('Color', colorSchema);

module.exports = Color;
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

小智 16

我遇到过同样的事情.我之前有这样的代码

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema();
    var schema = new Schema({
        path : {type:string , required:true},
        title: {type:string , required: true}
    })
 module.export = mongoose.model('game', schema);
Run Code Online (Sandbox Code Playgroud)

然后我使用下面的脚本解决了构造函数问题

   var mongoose = require('mongoose');
    var schema = mongoose.Schema({
        path : {type:string , required:true},
        title: {type:string , required: true}
    })
 module.export = mongoose.model('game', schema);
Run Code Online (Sandbox Code Playgroud)

  • 所以,这种技术也对我有用……但为什么呢?官方文档清楚地显示它用作带有 `new` 关键字的构造函数。而且,这是使用简单数据 - 不像上面的“对象内容”。http://mongoosejs.com/docs/guide.html (2认同)

Dia*_*aBo 7

在我的情况下,问题是最后应该 (s) 的导出:

问题:出口中缺少(s)

module.export = mongoose.model('Event', EventSchema);
Run Code Online (Sandbox Code Playgroud)

解决方案:将(s)添加到导出

module.exports = mongoose.model('Event', EventSchema);
Run Code Online (Sandbox Code Playgroud)


str*_*str 5

应该是Schema.Types.ObjectId,而不是Schema.ObjectIdhttp : //mongoosejs.com/docs/schematypes.html


小智 5

我通过导入大写模式解决了这个问题。

以前的:

const Scheme = mongoose.schema;
Run Code Online (Sandbox Code Playgroud)

修复后:

const Schema = mongoose.Schema;
Run Code Online (Sandbox Code Playgroud)

完整架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ItemSchema = new Schema({
    name : {
        type: String,
        required : true
    },
    date : {
        type : Date,
        default : Date.Now
    }
});
module.exports = mongoose.model('Item', ItemSchema);
Run Code Online (Sandbox Code Playgroud)