not able to acces db() from exported MongoClient module - javascript

I am not able to export the client properly from db.js to User.js
db.js
const some= MongoClient.connect(process.env.CONNECTIONSTRING).then((client) =>{
module.exports=client
const app = require("./app")
app.listen(process.env.PORT)
})
Using the client here , i can do methods like client.db().collection("users");
But i am not able to do using the user.js
User.js
const usersCollection = require("../db").db().collection("users");
This gives error saying const
usersCollection = require("../db").db().collection("users");
^
TypeError: require(...).db is not a function

I maybe wrong but in the callback function for MongoClient the first argument is the error and second argument is for client.(err,client)
so you are calling db() on error and not client
And also try to export from global scope as mentioned by Maxime in the comment

You have this problem because you are importing something that is asynchronous and when you do it in 1 line the client is not ready when you try to call it with db().collection("users").
You can verify if the async is the issue by changing your code to this:
const temp = require("../db")
setTimeout(() => {
temp.db().collection("users")
}, 1000)
You can also check here for an example how to do the connection to the DB properly https://www.terlici.com/2015/04/03/mongodb-node-express.html

Related

Getting type error from require function of module.exports in nodejs firebase cloud functions

I have a function that I am exporting and importing inside another file. Now this export function is used in a lot of place inside the application and it's working fine everywhere else but for some reason it's becoming undefined inside the cloud function
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const db = admin.firestore();
const {
checkAndGetApplicationMode,
} = require("../Utils/application-setup-functions");
exports.createCause = functions.https.onCall(async (data, context) => {
console.log("applicationMode check", checkAndGetApplicationMode); // Undefined
console.log("applicationMode check", checkAndGetApplicationMode()); // TypeError: checkAndGetApplicationMode is not a function
});
Although If I hover over it in my vs code it does give me reference to the actual function.
Here is the file structure for more information. I am using this checkAndGetApplicationMode function in many other files and it's working fine there. Also if I try require inside the function then works but if i require it outside the file then it gives undefined
File Stucture

exported object is undefined in nodejs

I am using multer in index.js and i need to use an object which has multer storage engine in other routes. So i have exported the object but the problem is when i i try to use it in the route file its undefined.
index.js
const storage = new GridFsStorage({//some config})
const upload = multer({storage})
app.use('/posts',postRouter)
//if i use the middleware upload.single('file') here, will it affect all the routes like(posts/a,posts/b)?
exports.upload = upload
postRouter.js
const index = require('../index')
setTimeout(() => {
console.log(index.upload)
}, 1000);
console.log(index.upload)
i tried using setTimeout and its giving me the expected result but outside settimmeout its undefined.
why is this happening. what is the best way to apply the multer middleware in some other routes by exporting it from index?
the problem is GridFs is taking sometime to connect and do its work, but before that this upload object is exported . thats why above scenario occurs. any idea how to avoid that?
As GridFsStorage is asynchronous, so it need some time to init. And you can just
pass upload as param to the postRouter function.
app.use('/posts', postRouter(upload))

Use a class method in router.get

I'm really new to node.js
and I'm having trouble when I'm using a class method in router.get callback
It gives me this error:
Can you guys help me out ?
Route.get() requires a callback function but got a [object object]
Here is my code
router.js :
const express = require('express');
const router = express.Router();
const test = require('../controller/controller');
router.get('/', test.testing());
module.exports = router;
controller.js :
class oop
{
testing(req,res)
{
console.log('okay');
}
}
exports.testing =new oop();
app.js :
const express = require('express');
const app = express();
app.listen(80);
const wiki = require('./routes/router');
app.use('/', wiki);
A callback function will be called in some arbitrary amount of time, therefore you need to provide a reference to the function... so when the time comes, Javascript can execute that function. In your case, you are not passing the function, but running it! test.testing(). What you are actually passing to the 'callback' parameter is the result of test.testing() which, in this case, is undefined

Understanding various parameters passed in export default

I was going through an article on web when I stumbled upon the following code snippet.
I this author have used babel to use ES6 syntax in node and have configured our app in two parts
App.js
Server.js
Inside our Server.js he have done something like this
import express from 'express';
import cors from 'cors';
const app = express();
function setPort(port = 5000) {
app.set('port', parseInt(port, 10));
}
function listen() {
const port = app.get('port') || 5000;
app.listen(port, () => {
console.log(`The server is running and listening at http://localhost:${port}`);
});
}
app.use(cors({
origin: '*', // Be sure to switch to your production domain
optionsSuccessStatus: 200
}));
// Endpoint to check if the API is running
app.get('/api/status', (req, res) => {
res.send({ status: 'ok' });
});
export default {
getApp: () => app,
setPort,
listen
};
Here this statement doesn't make sense to me
export default {
getApp: () => app,
setPort,
listen
};
And then in app.js, He have done this
import server from './server';
server.listen();
export default server;
Question: Can someone please explain me in stretch what is happening here? Like why is our getApp: () => app written like this and why setPort and listen written normally?
Ps: I know what does export default mean
The author is exporting an object with three properties as the default export.
Property 1: getApp -
This property has a value which is a function that returns the app variable from the server.js file, which is just the express instance. In other words, it is a method which returns the express app.
Property 2: setPort -
This property has a value equal to the setPort function defined in the server.js file
Property 3: listen -
This property has a value equal to the listen function defined in the server.js file
So when the author calls server.listen() in the app.js file, he/she is just calling the listen function which he/she has imported from the server.js file. Not exactly sure why they've chosen to set the app this way...
Well, put simply it's an inline function definition utilising ES6 arrow functions syntax which returns the internal app instance.
It's no different to:
getApp: function() {
return app;
}
The reason it's declared inline is because you don't actually have a function definition anywhere else in the module. If you added the function beforehand then it could be exported the same way as listen / setPort

Running Code When a Module is Loaded and Exposing It as Middleware

I am still trying to fully understand how exporting and importing modules works in Nodejs.
I am using the following file to seed a mongodb database. This file runs exactly as it should and returns exactly the result I am expecting, when I execute it as a standalone file. My issue is I want to use this file in two different places in my app. So I am trying to make it an exportable/importable module. Here is what I have tried:
seed.js looks like this:
'use strict';
// library modules
const {ObjectID} = require('mongodb');
const seeder = require('mongoose-seed');
const jwt = require('jsonwebtoken');
const util = require('util');
// local modules
const {Course} = require('./../models/course');
const {Review} = require('./../models/review');
const {User} = require('./../models/user');
const {data} = require('./../data/data.js');
const config = require('./../config/config.js');
/*==================================================
build seeding Courses, Reviews, Users
==================================================*/
// Connect to MongoDB via Mongoose
let seed = seeder.connect(process.env.MONGODB_URI, (e) => {
console.log(`Connected to: ${process.env.MONGODB_URI} and seeding files`);
// Load Mongoose models
seeder.loadModels([
'src/models/user.js',
'src/models/review.js',
'src/models/course.js'
]);
// Clear specified collections
seeder.clearModels(['User', 'Review', 'Course'], function() {
// Callback to populate DB once collections have been cleared
seeder.populateModels(data, function() {
seeder.disconnect();
});
});
});
module.exports = seed;
Within app.js I have these two lines
const seed = require('./middleware/seed');
and
app.use(seed);
I have also tried, to no avail
app.use(seed());
What is missing? I don't want to use the code in-line in two different places (DRY you know).
It is failing with this error:
throw new TypeError('app.use() requires a middleware function')
I am sorry about the formatting I thought I was using markdown, but I am clearly not.
You are executing your seeder function in that module and not returning any middleware function at all. Middleware is always a function and it has the form of:
const seed = function (req, res, next) {
...
next()
}
With what you have now, the best you can do is the following which will certainly seed your models when the module is loaded.
const seed = require('./middleware/seed');
Are you trying to run those two functions as middleware, on every request? In that case you'd do something like this:
const seed = function (req, res, next) {
seeder.connect(..., (e) => {
...
seeder.clearModels(..., ()=>{
...
next()
})
})
})
If you want to run that seeder code at the module level AND to expose it as middleware then wrap the current module level code in function and execute it when the module loads. Notice that the new function optionally handles the next callback if it receives it.
function doSeed(next){
//your code currently running at module level
if(next)
return next()
}
doSeed(); //run the code at the module level
const seed = (req, res, next) => doSeed(next))
module.exports = seed;
One way that I allow myself to have access to a variable in different instances is adding it to the process variable. In node.js no matter where in the project it is, it will always be the same. In some cases, I would do process.DB = seed(); which would allow process.DB to always be the result of that. So inside your main class you can do process.DB = seed(); and all of your other classes running off of that one main class would have access to process.DB keeping your database readily available.

Categories