Sequelize object is not a function - node.js

I am working from this repo and trying to convert it over to PostgreSQL here is my error:
/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601
this.importCache[path] = defineCall(this, DataTypes);
^
TypeError: object is not a function
at Sequelize.import (/home/otis/Developer/Shipwrecked/Hatchway/node_modules/sequelize/lib/sequelize.js:601:30)
at db.sequelize (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:15:37)
at Array.forEach (native)
at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/models/index.js:14:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/app.js:10:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/otis/Developer/Shipwrecked/Hatchway/bin/www:7:11)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Here is the code that is causing the error (models/index.js):
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "development";
var config = require(__dirname + '/../config.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
If I comment out the following lines the error stops:
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Node.js errors are not my strong point so I am not really sure what is going, on I can also post my config.json if that is needed?

If we look at the code imports:
if (!this.importCache[path]) {
var defineCall = (arguments.length > 1 ? arguments[1] : require(path));
this.importCache[path] = defineCall(this, DataTypes);
}
...it will be understood that it looks like a folder with the models have a file that is not a valid model file and generally correct module. Accordingly, in an attempt to activate it via the "desirable" get errors. Check folder models.

Related

TypeError: require(...) is not a function with typescript

I'm using typescript to run a sequelize database, and any time I run npm run build, I keep getting this error. I don't know what to do because I have checked online and the solutions don't work for me. All I'm trying to do is to connect to the database using sequelize database.
TypeError: require(...) is not a function
at C:\Users\Boss\Desktop\Microservice Api\models\index.ts:24:54
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\Boss\Desktop\Microservice Api\models\index.ts:23:4)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Module._compile (C:\Users\Boss\Desktop\Microservice Api\node_modules\source-map-support\source-map-support.js:568:25)
at Module.m._compile (C:\Users\Boss\AppData\Local\Temp\ts-node-dev-hook-515725030064434.js:69:33)
at Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at require.extensions..jsx.require.extensions..js (C:\Users\Boss\AppData\Local\Temp\ts-node-dev-hook-515725030064434.js:114:20)
at require.extensions.<computed> (C:\Users\Boss\AppData\Local\Temp\ts-node-dev-hook-515725030064434.js:71:20)
at Object.nodeDevHook [as .ts] (C:\Users\Boss\Desktop\Microservice Api\node_modules\ts-node-dev\lib\hook.js:63:13)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\Boss\Desktop\Microservice Api\server.ts:4:1)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Module._compile (C:\Users\Boss\Desktop\Microservice Api\node_modules\source-map-support\source-map-support.js:568:25)
at Module.m._compile (C:\Users\Boss\AppData\Local\Temp\ts-node-dev-hook-515725030064434.js:69:33)
at Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at require.extensions..jsx.require.extensions..js (C:\Users\Boss\AppData\Local\Temp\ts-node-dev-hook-515725030064434.js:114:20)
at require.extensions.<computed> (C:\Users\Boss\AppData\Local\Temp\ts-node-dev-hook-515725030064434.js:71:20)
at Object.nodeDevHook [as .ts] (C:\Users\Boss\Desktop\Microservice Api\node_modules\ts-node-dev\lib\hook.js:63:13)
[ERROR] 19:32:13 TypeError: require(...) is not a function
This is my index.ts file where i keep getting the error
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env];
const db: any = {};
let sequelize: any;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file: string) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.ts');
})
.forEach((file: any) => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes) ;
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.account = require('./account')(sequelize, Sequelize)
db.phone_number = require('./phone_number')(sequelize,Sequelize)
db.account.hasMany(db.phone_number, {
foreignKey:'account_id'
})
db.phone_number.belongsTo(db.account)
export default db;
The error is coming from my index.ts folder. i don't know why I'm getting this error.
.forEach((file: any) => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes) ;
db[model.name] = model;
});

module.js:549 throw err;

> module.js:549
> throw err;
> ^
>
> Error: Cannot find module '..models/category'
> at Function.Module._resolveFilename (module.js:547:15)
> at Function.Module._load (module.js:474:25)
> at Module.require (module.js:596:17)
> at require (internal/module.js:11:18)
> at Object.<anonymous> (/home/mridul/shafee-it/routes/admin.js:2:18)
> at Module._compile (module.js:652:30)
> at Object.Module._extensions..js (module.js:663:10)
> at Module.load (module.js:565:32)
> at tryModuleLoad (module.js:505:12)
> at Function.Module._load (module.js:497:3)
> at Module.require (module.js:596:17)
> at require (internal/module.js:11:18)
> at Object.<anonymous> (/home/mridul/shafee-it/server.js:74:21)
> at Module._compile (module.js:652:30)
> at Object.Module._extensions..js (module.js:663:10)
> at Module.load (module.js:565:32) [nodemon] app crashed - waiting for file changes before starting...
Here is my ..models/category(category schema)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
name: { type: String, unique: true, uppercase: true}
});
module.exports = mongoose.model('Category', CategorySchema);
add-category Route in admin.js file
const router = require('express').Router();
const Category = require('..models/category');
// add-category route
router.get('/add-category', function(req, res, next) {
res.render('admin/add-category', { message: req.flash('success') });
});
router.post('/add-category', function(req, res, next) {
var category = new Category();
category.name = req.body.name;
category.save(function(err) {
if (err) return next(err);
req.flash('success', 'Successfully added a category');
return res.redirect('/add-category');
});
});
Here also server.js file to include the category
const Category = require('./models/category');
app.use(function(req, res, next) {
Category.find({}, function(err, categories) {
if (err) return next(err);
res.locals.categories = categories;
next();
});
});
const adminRoutes = require('./routes/admin');
app.use(adminRoutes);
when i run my server or route the add-category url then show module.js:549 throw err; this problem.
Here is my problem details and i check my code different times.
Then how can i solve this problem.
Seems to me that you forgot a /:
require('..models/category');
require('../models/category');
This is why ..models/category throws an error. From a general point of view, when require can't find a local module, don't "check the code", just check where the file is, and what path you wrote, it's always one or the other. ;)

node.js - TypeError: db.model is not a function

New to node and mongodb
I am working on a linux Centos 7 enviorment.
For some reason I get this error 'TypeError: db.model is not a function'
What does this error means?
/var/www/html/mongo/crud/src/model/task.js:11
return db.model('tasks',Task);
^
TypeError: db.model is not a function
at module.exports (/var/www/html/mongo/crud/src/model/task.js:11:15)
at Object.<anonymous> (/var/www/html/mongo/crud/src/routes/index.js:4:39)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/html/mongo/crud/src/app.js:9:21)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
[nodemon] app crashed - waiting for file changes before starting...
this is the content of task.js file:
module.exports = function(){
var db = require('../libs/db-connection')();
var Schema = require('mongoose').Schema;
var Task = Schema({
title: String,
description: String,
status: Boolean
});
return db.model('tasks',Task);
}
This the content of index.js file:
const express = require('express');
const router = express.Router();
const model = require('../model/task')();
router.get('/' ,(req, res) => {
model.find({}, (err, tasks) =>{
if (err) throw err;
res.render('index', {
title: 'CRUD',
task: tasks
});
});
});
module.exports = router;
Unless you have a model function in your libs/db-connection, I think that you want to use the model from mongoose.
If this is right, to fix your problem you need to change the import from mongoose, like this:
var mongoose = require('mongoose'); // Not require('mongoose').Schema (because you need schema and model)
var Task = mongoose.Schema({ // Call Schema from mongoose
title: String,
description: String,
status: Boolean
});
return mongoose.model('tasks',Task); // Call model from mongoose

Auto increment field in mongoose

Im trying to create auto increment field in mongoose but i cant create for some reason
This is my app.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Artist = require('./models/artist');
mongoose.connect('mongodb://localhost/auto-increment');
app.get('/', function(req, res){
Artist.create({
name: "artistName",
fpimage: "Cover"
}, function(err, artist){
if(err) {
console.log(err);
} else {
artist.save();
console.log(artist);
res.send('Hi ')
}
});
});
// Set Port
app.set('port', (process.env.PORT || 3000));
// Run Server
app.listen(app.get('port'), function(){
console.log('Server has started on Port: '+app.get('port'));
});
and this is my artist model
var mongoose = require("mongoose");
var autoIncrement = require('mongoose-auto-increment');
var artistSchema = new mongoose.Schema({
name: String,
fpimage: String
});
artistSchema.plugin(autoIncrement, 'Artist');
module.exports = mongoose.model('Artist', artistSchema);
When i run the app, i get following the error message
fn(this, opts);
^
TypeError: fn is not a function
at Schema.plugin (C:\Users\tjesu\Desktop\pidal\auto-increment\node_modules\mongoose\lib\schema.js:1060:3)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\models\artist.js:10:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\app.js:4:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
How can i fix this error? What should i do?
From the docs, it looks like you're missing two things:
You need to initialize autoIncrement:
autoIncrement.initialize(mongoose.connection);
You need to change your call to:
artistSchema.plugin(autoIncrement.plugin, 'Artist');
use autoIncrement.plugin instead of autoIncrement in your model
like:
artistSchema.plugin(autoIncrement.plugin, 'Artist');
and need initialize autoIncrement once
var connection = mongoose.createConnection("mongodb://localhost/auto-increment");
autoIncrement.initialize(connection);
and can use get like
app.get('/', function(req, res){
var artist = new Artist({name: "Telmuun",fpimage: "Cover"});
artist.save(function(err, saved) {
if(err) {
console.log(err);
}
else {
res.send('saved');
}
});
});

util.inherits throws TypeError: Cannot read property 'prototype' of undefined

app.js
var Website = new require( './jslib/website.js' );
./jslib/website.js
var util = require('util'),
events = require('events');
module.exports = Website;
function Website()
{
events.EventEmitter.call( this );
return this;
}
util.inherits( Website, events.EventEmiter );
Console Output
PATH_TO_APPDIR>node app.js
util.js:538
ctor.prototype = Object.create(superCtor.prototype, {
^
TypeError: Cannot read property 'prototype' of undefined
at Object.exports.inherits (util.js:538:43)
at Object.<anonymous> (PATH_TO_APPDIR\jslib\website.js:9:6)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at new require (module.js:378:17)
at Object.<anonymous> (PATH_TO_APPDIR\app.js:1:16)
at Module._compile (module.js:449:26)
This is NodeJS 8.22 on Windows 7*
You have a typo in your code.
util.inherits( Website, events.EventEmiter );
Should be
util.inherits( Website, events.EventEmitter );

Resources