I'm building a cafe website with NodeJS, Express, and Mongo. I'm attempting to create a new cafe in one of my routes with a get request using a model I created. However, I keep getting an TypeError in my terminal stating that Cafe is not a constructor. I don't understand because I have defined the Schema in a separate file and I've included it in my app.js (routes file). Any feedback about this error is appreciated. I've included a few photos along with the code. Thank you in advance!
const path = require('path')
const mongoose = require('mongoose');
const Cafe = require("./models/cafe");
mongoose.connect('mongodb://localhost:27017/cafe-hopping', {
useNewURLParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express()
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/createcafe', async(req, res) => {
const cafes = new Cafe ({ name: 'Cueva Matera', description: "A cave like theme cafe"});
await cafes.save();
res.send(cafes)
})
*The following is the Schema (the file name is cafe.js)*
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CafeSchema = new Schema({
name: String,
price: String,
description: String,
location: String
});
module.export = mongoose.model('Cafe', CafeSchema);
[![app.js file. This is where I am keeping all of my routes][1]][1]
[![cafe.js file. This is where I create a new Schema for the database][2]][2]
[![This is the server error message I'm getting in my terminal every time I send the /createcafe get request][3]][3]
[1]: https://i.stack.imgur.com/mgTYg.png
[2]: https://i.stack.imgur.com/p9Ibx.png
[3]: https://i.stack.imgur.com/hFzzJ.png
CodePudding user response:
The issue appears to be that you should be using
module.exports = mongoose.model('Cafe', CafeSchema);
Instead of module.export
Because of the misnamed property (export
vs exports
) the schema is not getting exported correctly, and Cafe
is not a constructor.