【问题标题】:Mongoose and new Schema: returns "ReferenceError: Schema is not defined"Mongoose 和新架构:返回“ReferenceError:架构未定义”
【发布时间】:2014-09-14 12:21:13
【问题描述】:

我正在创建一个新的示例应用程序,我尝试通过 Mongoose 连接到 MongoDB 数据库。

我在service.js 文件中创建了一个新架构,但在运行nodemon app.js 时出现以下错误:"ReferenceError: Schema is not defined"

App.js 代码:

var http = require('http');
var express = require('express');
var serials = require('./service');
var app = express();
var mongoose = require('mongoose');


var port = 4000;
app.listen(port);

mongoose.connect('mongodb://localhost:27017/serialnumbers')

app.get('/api/serials',function(req,res){
    serials.getSerial(req, res, function(err, data) {
        res.send(data);
    });
});

Service.js 代码:

var mongoose = require('mongoose');

var serialSchema = new Schema({
    serial: {type: String},
    game: {type: String},
    date: {type: Date, default: Date.now},
});
mongoose.model('serials', serialSchema);

exports.getSerial = function(req,res,cb) {
    mongoose.model('serials').find(function(err,data) {
        cb(err,data);
    });
};

我在 StackOverflow 上看到了一个答案,其中提到它可能是 Mongoose 的版本。但是npm list 给了我这个:

知道我做错了什么吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    确切地说,在您的Service.js 中,Schema 是什么?您没有名为 Schema 的对象。

    ...
    var serialSchema = new Schema({
                           ^^^^^^
    

    改成mongoose.Schema就可以了。

    【讨论】:

    • 或在var mongoose = reguire('mongoose');下方添加var Schema = mongoose.Schema;
    【解决方案2】:

    你忘了在你的第二行定义这样的模式

    var Schema = mongoose.Schema

    【讨论】:

    • 对不起,这个答案不会为现有答案添加任何新内容。
    • 如果您在 Schema 定义中使用像 'Schema.Types.Mixed' 这样的对象,这会更有意义。比 'mongoose.Schema.Types.Mixed' 更容易查看,但可能不太明确。
    【解决方案3】:

    这可能是由于多种原因造成的。第一个是您可能忘记导入 Schema。您可以按如下方式解决。

    const Schema = mongoose.Schema;
    
    const serialSchema = new Schema({
       serial: {type: String},
       game: {type: String},
       date: {type: Date, default: Date.now},
    });
    

    有时您忘记导入新创建的模型。此类错误可以通过将创建的模型导入您的工作文件来解决。

    const serialModel = mongoose.model('serials', serialSchema);
    

    【讨论】:

      【解决方案4】:

      在我的例子中,我在另一个模式中引用了一个模式,并且不得不将 type: Schema.Types.ObjectId 替换为 mongoose.Types.ObjectId。

      【讨论】:

        【解决方案5】:

        在你的情况下调用mongoose.Schema,因为你没有定义它

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

        【讨论】:

          【解决方案6】:

          在你的 var 猫鼬 = 要求('猫鼬'); 和 var serialSchema = new Schema({ 添加 Const Schema= mongoose.Schema

          定义架构并解决问题

          【讨论】:

          • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 1970-01-01
          • 2016-05-17
          • 2015-04-21
          • 1970-01-01
          • 2012-02-10
          • 2016-10-26
          • 2022-12-05
          • 2019-12-16
          • 2014-02-17
          相关资源
          最近更新 更多