Reputation: 9986
I am creating a new sample application, where I try to connect to a MongoDB database through Mongoose.
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"
App.js code:
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:
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 StackOverflow that referenced it could be the version of Mongoose. But npm list
gives me this:
Any idea what I am doing wrong?
Upvotes: 18
Views: 43655
Reputation: 91
Define Schema
like this on your second line:
var Schema = mongoose.Schema
Upvotes: 9
Reputation: 21
const { Schema } = mongoose;
From: https://mongoosejs.com/docs/guide.html#definition
Upvotes: 2
Reputation: 124
Between your var mongoose = require('mongoose'); and var serialSchema = new Schema({ Add Const Schema= mongoose.Schema
That defines the schema and solves the problem
Upvotes: -1
Reputation: 31
In my case, I was referencing a schema inside of another schema and had to replace type: Schema.Types.ObjectId with mongoose.Types.ObjectId.
Upvotes: 1
Reputation: 1452
In you case call as mongoose.Schema
as you did not defined it as
const mongoose = require('mongoose');
then
const Schema = mongoose.Schema;
Upvotes: 0
Reputation: 2639
This can be occurred due to several reasons. first one is that you might forgotten to import Schema.You can fix that as follows.
const Schema = mongoose.Schema;
const serialSchema = new Schema({
serial: {type: String},
game: {type: String},
date: {type: Date, default: Date.now},
});
Sometimes you have forgotten to import your newly created model.This type of errors can be solve by importing created model to your working file.
const serialModel = mongoose.model('serials', serialSchema);
Upvotes: 5
Reputation: 6487
Exactly, in your Service.js
, what is Schema
? You don't have an object named Schema
.
...
var serialSchema = new Schema({
^^^^^^
change it to mongoose.Schema
then it will be fine.
Upvotes: 37