mongodb : TableRow.TableRow is not a constructor - javascript

I am getting-started with mongodb.
I have set-up all the mongodb and the mongoose configuration and they work perfectly.
Here are the project files:
server.js:
const TableRow = require('./models/tableRow');
const bodyParser = require('body-parser');
const cors = require('cors')
const express = require('express');
const mongoose= require('mongoose')
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/table', function(err) {
if (err) { throw err; }
console.log('Successfully connected');
});
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
app.use('/', router);
router.route('/table/add').post((req, res) => {
let tableRow = new TableRow (req.body);
tableRow.save()
.then(issue => {
res.status(200).json({'tableRow': 'Added successfully'});
})
.catch(err => {
res.status(400).send('Failed to create new record');
});
});
app.listen(5757, () => console.log(`Express server running on port 5757`));
tableRow.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let TableRow = new Schema({
column1Data: {
type: String
},
column2Data: {
type: String
}
});
export default mongoose.model('TableRow', TableRow);
When I tried testing this with POSTMAN:
I get this error:
TypeError: TableRow is not a constructor
I think the problem is with the way I required the model in server.js:
const TableRow = require('./models/tableRow');
Someone else faced a similar issue and posted it on stackOverFlow. However, they are defining the model in the same file the server code.
Similar issue but doesn't solve my problem
So his post doesn't solve my issue.
Any idea how I can fix this?

Change from
export default mongoose.model('TableRow', TableRow);
To this:
module.exports = mongoose.model('TableRow', TableRow);
And import so: const TableRow = require('./models/tableRow');
It's CommonJS module specification which is the standard used in Node.js for working with modules (more info).
When using Node.js, including express framework, you should do it so.
module.exports is the object that's actually returned as the result of a require call.(Reference)
Remember:
You must use both import and export syntax from the same standard.
A brief summary of two module systems:
Today there are two module systems that are actively being used. CommonJS (CJS) is what Node.js has used historically. ESM (EcmaScript modules) is a newer system which has been added to the JavaScript specification. Browsers already support ES modules, and Node is adding support. (source)

Related

What does 'dbo' stands for in MongoDB - Express app?

Here is the code example:
app.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, () => {
// perform a database connection when server starts
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
db/conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("employees");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
I've done some research and it stands for 'Database Owner' in SQL Server but it doesn't make sense here.
These code examples are from MongoDB official documentation and why do they assign connection instance as dbo if it really stands for Database Owner?
As the documentation provides no explanation for the choice of variable name, we can only guess. My best guess is that dbo stands for database object, considering the type of the export.
I think this is idiosyncratic usage mimicked from the SQL world where dbo is the default schema and abbreviates database owner.
Typically, and in the MongoClient documentation, I see just db = require("./db/conn"); But it appears here that the author's fingers are just used to automatically typing an o after typing db.
Humans are habitual imitators. I wouldn't think too much of it. It's just a variable name.
There is no restriction and built-in parameters name in nodejs.
You can use that according to your preference

Error: Cannot find module './keys_dev' Require stack

I have cloned a GitHub repo for reference. But i don't know what this .keys_dev refers to. Everything seems fine to me. But it is returning me error. Everything is in its place as expected. I hope anyone can help me. It requires stack that is unknown to me. It is requiring api that is already defined. I need to understand can anyone help?
const express = require("express");
const bodyPaser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
const users = require('./routes/api/users');
const level = require('./routes/api/levels');
const employee = require('./routes/api/employees');
const exception = require('./routes/api/exception');
const payslip = require('./routes/api/payslip');
const dashboard = require('./routes/api/dashboard');
const individualcost = require('./routes/api/individualcost');
const oneoffpayment = require('./routes/api/oneoffpayment');
const record = require('./routes/api/record');
const app = express();
//Body parser middleware
app.use(bodyPaser.urlencoded({ extended: false }));
app.use(bodyPaser.json());
app.use(cors())
//Db
const db = require("./config/keys").mongoURI;
//MongoDB connection
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport Middleware
app.use(passport.initialize());
//Passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/users', users);
app.use('/api/level', level);
app.use('/api/employee', employee);
app.use('/api/exception', exception);
app.use('/api/payslip', payslip);
app.use('/api/dashboard', dashboard);
app.use('/api/individualcost', individualcost);
app.use('/api/oneoffpayment', oneoffpayment);
app.use('/api/record', record);
// Server static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`App is running on port ${PORT}`));
const db = require("./config/keys").mongoURI;
This require is fetching application configurations from the local filesystem, in this case the db URI. Perhaps the author of the repo forgot to mention that detail? It's very likely that if you want to use a MongoDB you'll have to setup your own local or cloud database and create a file under config/keys that contains a mongoURI. This should look similar to this:
// this is the contents of ./config/keys
export default {
mongoURI: "mongodb+srv://project:your-mongo-uri-here",
};
If you're looking to start a mongo cluster on the cloud, I've been using cloud.mongodb for a small pet project, works like a charm and it has a free plan tier.
You can also run mongo locally and just point the mongoURI to your local mongo instance.

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

I used mongoose to connect my database to my app.
I got this unexpected error.
My app.js look like this
const express = require('express');
const mongoose = require('mongoose');
const authRoutes = require('./routes/authRoutes');
const cookieParser = require('cookie-parser');
const { requireAuth, checkUser } = require('./middleware/authMiddleware');
const run = require('./admin/connection');
const app = express();
// middleware
app.use(express.static('public'));
app.use(express.json());
app.use(cookieParser());
const {default : AdminBro} = require('admin-bro');
const buildAdminRouter = require('./admin/admin.router');
const options = require('./admin/admin.options');
const port = 3000;
const url = 'mongodb://localhost:27017/dbName';
let mongooseDb;
const databaseConnect = async () => {
mongooseDb = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true })
.then((result) => app.listen(3000))
.catch((err) => console.log(err));
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("we are connected to database");
});
const admin = new AdminBro(options)
const router = buildAdminRouter(admin);
app.use(admin.options.rootPath, router);
};
databaseConnect();
I already installed mongodb database.
I already find similar question in stackoverflow but that answers didn't resolve my issue. Any help will be appreciated. Thanks
If It's MAC OS, run following command and try again:
brew services restart mongodb-community
the commands that follow will be the following:
Stopping mongodb-community... (might take a while)
==> Successfully stopped mongodb-community (label: homebrew.mxcl.mongodb-community)
==> Successfully started mongodb-community (label: homebrew.mxcl.mongodb-community)
I faced a similar problem.Give a try to this one:
Open your C drive.
Make a folder named 'data'.
Make another folder inside this data folder name 'db'.
You can see in the documentation that By default MongoDB try to search these directories, We have to create these manually
This error occurs when you run your node app without a server.
Fix is to run your mongodb server first then your app.

Cant connect to MongoDB in Firebase Functions

I am using Firebase Functions as the host for my MERN web app backend.
When I connect to MongoDB locally, it works and can run operations with the database. However, when I deployed to firebase functions, it failed to even connect to the database.
Code:
index.js
const functions = require('firebase-functions');
const server = require('./server.js');
exports.api = functions.runWith({ memory: "2GB", timeoutSeconds: 120 }).https.onRequest(server);
Part of server.js
const express = require("express");
const dotenv = require("dotenv");
const colors = require("colors");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const bodyParser = require("body-parser");
const routes = require("./routes/routes.js");
const mongooseMethods = require("./database.js");
dotenv.config({ path: "./config/config.env" });
mongooseMethods.connectDB(process.env.MONGO_URL);
const PORT = process.env.PORT || 8080;
// set up app
const app = express();
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
app.use("/api", routes); // /api routes
module.exports = app;
routes.js
const express = require("express");
const app = express.Router();
const testingApi = require('../controller/testing.js');
const authApi = require('../controller/auth.js');
// testing
app.get('/testing', testingApi.testing);
// user authentication
app.post('/user/register', authApi.createUser);
module.exports = app;
api/testing/ also works
database.js
const mongoose = require("mongoose");
const mongooseMethods = {
connectDB: async (url) => {
try {
console.log("Connecting to MongoDB")
const connection = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(`MongoDB Connected: ${connection.connection.host}`.cyan.bold);
return connection;
} catch (error) {
console.log(`Error: ${error.message}, Exiting`.red.bold);
process.exit(1);
}
}
}
module.exports = mongooseMethods;
auth.js
const User = require('../model/user.model.js');
const bcrypt = require("bcryptjs");
let authenticationApi = {
createUser: async (req, res) => {
try {
console.log("Creating");
let newUser = new User({
...req.body
})
let result = await newUser.save();
return res.status(200).json({ result: result });
} catch (error) {
return res.status(400);
}
}
}
module.exports = authenticationApi;
The error I received when sending request to firebase is
2020-02-27T02:34:46.334044912Z D api: Function execution took 30970 ms, finished with status: 'connection error'
Yet it runs perfectly fine in local. I also don't see the console log "connected to MongoDB". I'm guessing that the problem occurs in database.js that it failed to connect to mongo at the first place yet I don't know how to solve.
I am using the paid plan in Firebase and the outbound networking should be fine.
p.s. this is my first time posting here. thanks for your time and I apologize in advance if i'm breaking any rules.
Listening on a port is not a valid operation in cloud functions:
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
Cloud Functions listens for you, using the URL that it was assigned, then delivers the request to your code. When you pass your express app to onRequest(), that's all wired up for you.
I suggest starting with a stripped down, simplified version of an app just to gain experience about how things work, then add in more as you get comfortable.
The reason for this to happen is that the architecture of Firebase Functions is not an actual server, but a serverless lambda-like endpoint. Since it cannot establish a lasting connection to the database, that it has to make a connection every time it received a request, the database sees this as spam and shut down further connection request from Firebase.
Therefore, you simply cannot host a complete express app with intended lasting connection in Firebase Functions.
More on that in this article

Could somebody explain how to pass globally the database variable in express.js?

already tried a lot of tutorials, but somehow I could not figure it out.
I am using mongodb and express.js
this is in my server.js
const express = require('express');
const subdomain = require('express-subdomain');
const bodyParser= require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const routes = require('./routes');
const app = express();
var db;
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('views'));
app.use(subdomain('api', routes.api));
MongoClient.connect('mongodb://localhost:27017/test', (err, database) => {
if (err) return console.log(err);
db = database;
app.listen(3000, () => {
console.log('listening on 3000');
});
});
and this is in my routes.js
const express = require('express');
const api = express.Router();
api.get('/', function (req, res) {
db.collection('test').find().toArray((err, result) => {
if (err) return console.log(err);
res.render('api_orders', {test: result});
});
});
module.exports = {
api
}
I would like to use the db variable also in routes, but it always gives me the db is not defined error (obviously) I read that I should somehow export the db var, but could not managed to do it
Instead i would suggest you to create another file and you just require it where you want to use it. Suppose:
db.js:
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/test', (err, database) => {
if (err) return console.log(err);
return database;
});
}
module.exports = db;
Now you can use the db anywhere when you do :
const mydb = require('./db'); // <--require it to use
It may not work as it is not tested but it can give you idea to get through.
This is as much a question as a response. I've used
MongoClient.connect('mongodb://localhost:27017/test', (err, database)={
global.bigdb = database
});
and called it from the routes for instance
var col = global.bigdb.collection('collectionname');
Is this bad practice? Rereading the code - it's been live for a while - I'm also exposing the redis client as a global.
Any info appreciated. Live with no bug reports but very curious if I should refactor.
app.use(function(req,res,next))
{
res.locals.yourvariable = null;
next();
});
This is how I initialize global variables. Hope you get an idea.

Categories

Resources