Mongoose和new Schema:返回“ReferenceError: Schema未定义”

时间:2022-02-05 02:33:39

I am creating a new sample application, where I try to connect to a MongoDB database through Mongoose.

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

I create a new schema in my service.js file, but I get the following error when I run nodemon app.js: "ReferenceError: Schema is not defined"

我在我的服务中创建了一个新的模式。js文件,但是运行nodemon应用程序时,我得到了以下错误:“ReferenceError: Schema未定义”

App.js code:

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 code:

服务。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);
    });
};

I saw an answer here on * that referenced it could be the version of Mongoose. But npm list gives me this:

我在*上看到了一个答案它可能是Mongoose的版本。但是npm列表告诉我:

Mongoose和new Schema:返回“ReferenceError: Schema未定义”

Any idea what I am doing wrong?

知道我做错了什么吗?

2 个解决方案

#1


21  

Exactly, in your Service.js, what is Schema? You don't have an object named Schema.

确切地说,在你的服务。js,模式是什么?您没有一个名为Schema的对象。

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

change it to mongoose.Schema then it will be fine.

改变它的猫鼬。这样就可以了。

#2


2  

you forgot to define the Schema like this on you second line

您忘记在第二行中定义模式

var Schema = mongoose.Schema

var模式= mongoose.Schema

#1


21  

Exactly, in your Service.js, what is Schema? You don't have an object named Schema.

确切地说,在你的服务。js,模式是什么?您没有一个名为Schema的对象。

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

change it to mongoose.Schema then it will be fine.

改变它的猫鼬。这样就可以了。

#2


2  

you forgot to define the Schema like this on you second line

您忘记在第二行中定义模式

var Schema = mongoose.Schema

var模式= mongoose.Schema