Getting mongoose not defined error in model file - node.js

mongoose module already installed also included in index.js
In index.js
mongoose = require('mongoose').connect(config.dbURL),
...
require('./routes/routes.js')(express, app);
In routes.js
var Category = require('../models/category');
...
Within model folder category.js
var categorySchema = mongoose.Schema({
category_name:String,
alias:String,
added_on:String
});
but error occurred while using in model file.
Folder structure:
server
-> index.js
-> routes/routes.js
-> models/category.js

Please add this line in category.js pages top :
var mongoose = require('mongoose');

Related

Express.js Type Error When Importing DB Schema

Creating a small web app on the MEAN stack and I'm in the process of migrating my schemas to a separate "models" directory. When the schemas are defined in the same app.js file, everything works fine; however, when I switch the code to a separate more modular file and import it I get this error:
TypeError: Player.find is not a function
at /Users/username/code/express/WebApp/v3/app.js:57:12
This error occurs when it gets to that first route where it needs to look players up and I'm not quite sure what I'm missing after staring at this for hours.
My app.js file:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
Player = require("./models/players")
const port = 3000;
mongoose.connect("mongodb://localhost/players", { useNewUrlParser: true, useUnifiedTopology: true });
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
// PLAYER SCHEMA ORIGNALLY DEFINED HERE BUT NOW ATTEMPTING TO MOVE TO DIFF DIRECTORY & IMPORT
/*var playerSchema = new mongoose.Schema({
player: String,
position: String,
description: String
});
var Player = mongoose.model("Player", playerSchema);*/
app.get("/", function(req, res) {
res.render("landing");
});
app.get("/players", function(req, res) {
// Get all players from DB
Player.find({}, function(err, allPlayers){
if(err){
console.log(err);
} else {
console.log("We're good.");
res.render("players", {players: allPlayers});
}
});
});
and my player.js file that I'm attempting to import:
var mongoose = require("mongoose");
var playerSchema = new mongoose.Schema({
player: String,
position: String,
description: String
});
// Compile into a model
module.exports = mongoose.model("Player", playerSchema);
The above schema definition and model definition work completely fine when they're in the app.js file, but not when imported. What am I missing here? Thanks in advance for the help.
I think your file name is wrong at the require statement. Its
const Player = require('../models/player')
as your file name is player.js, not players.js and if you stored the js file in a model folder. Do check out how to navigate using the file path
/ means go back to the root folder, then traverse forward/downward.
./ means begin in the folder we are currently in and traverse forward/downward
../ means go up one directory, then begin the traverse.
And also your backend should look like this.
Backend File Management

how to put a model in a different file in Sequelize

I have a new express.js application and I want to put my model in a different file using sequelize.
In my root dir I have a db.js that have this code
const Sequelize = require('sequelize');
// connect to MySql database
const db = new Sequelize('mysql://root:password#localhost:8889/myDB');
module.exports = db;
I'm exporting the db
Now in my root directory I have a models folder and inside the model folder I have a user.js file and in there I have this code.
const Sequelize = require('sequelize')
const db = require('../db')
const user = db.def('user', {
firstName: {
type: Sequelize.STRING
}
})
module.exports = user;
this give me this error.
db.def is not a function
I have merge the two files together it works, but it doesn't work i I break it in two separate files it doesn't.
It there's something I don't understand about export modules?

Understanding mongoose connections in express.js

I am learning express.js using the following project:
https://github.com/scotch-io/easy-node-authentication/tree/linking
In server.js I can see and understand the following initiates a connection to the database using the url from database.js:
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
/app/models/user.js contains the following:
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
},
...
}
module.exports = mongoose.model('User', userSchema);
Finally /config/passport.js contains:
var User = require('../app/models/user');
I can see how passport.js obtabs the model from user.js however I am failing to understand how user.js is aware of the connection setup in server.js as the initiated object "mongoose" is not exported?
What am I missing?
as you can see in this file index.js at the last line
var mongoose = module.exports = exports = new Mongoose;
this mean, Mongoosee will export only one instance (singleton) to handler database operations. because you first create connection in your server.js file, after that, any included/require model will have connection to your db server. all app will work on single object.

Cannot Find Module in the models folder

I have this basic structure ./api/controllers/authenticate.js and ./api/models/authenticate.js I want my controller to access the authenticate.js in the models folder as seen here.
controllers/authenticate.js
var app = require("express");
var router = app.Router();
var model = require("./api/models/authenticate.js");
router.get('/login',function(req,res){
res.send(model.authenticate());
});
module.exports = router;
models/authenticate.js
var authenticate = function() {
return "You should see this module";
}
module.exports = authenticate;
However I am getting a can not find the authenticate.js module in the models file. What am I missing?
controllers/authenticate.js
var app = require("express");
var router = app.Router();
var model = require("../models/authenticate.js");
router.get('/login',function(req,res){
res.send(model.authenticate());
});
module.exports = router;
var model = require("./api/models/authenticate.js"); is wrong as you are already in /api/controllers/ directory and you are trying to access the models directory so you have to come one step back by using ../ then entering into models. your case trying to access a directory inside the models directory inside the controller directory

Nodejs Mongoose - Model not defined

I'm trying to send some data to a database using mongoose. Here is my code so far.
server.js
var express = require('express');
var wine = require('./routes/wines');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.listen(3000);
console.log('Listening on port 3000...');
wine.js (inside models folder)
var mongoose = require('mongoose');
var db = mongoose.connection;
var wineSchema = new mongoose.Schema({
name: String,
description: String
});
var Wine = mongoose.model('Wine', wineSchema);
module.exports = Wine;
wines.js (inside routes folder)
exports.addWine = function(req, res) {
// Problem not defined here
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};
I keep getting this error and i have no idea why.
ReferenceError: Wine is not defined
I've exported Wine in wine.js (models), shouldn't I be able to use it everywhere ?
Thank you in advance !
Add var Wine = require('./../models/wine.js'); at the beginning of wines.js (assuming your routes and models folders are contained within the same directory).
Exporting objects/values/functions from node modules does not make them globally available in other modules. The exported objects/values/functions are returned from require (reference here for more info). That said, Mongoose uses an internal global cache for models and schemas which make it available via mongoose (or a connection) throughout an app.
So in your routes file you could do something like:
var Wine = mongoose.model('Wine'); // Notice we don't specify a schema
exports.addWine = function(req, res) {
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};

Resources