is there a way to create a separate file for mongodb operation functions and use those functions in index file?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



is there a way to create a separate file for mongodb operation functions and use those functions in index file?



i have main code in index.js file with express server, and i want to create another file just to handle database CRUD operations. How can i do the following?



index.js
import functions from mongo.js


getUsers()



mongo.js


using MongoClient.connect to connect to db
function getUser()
// get users from mongo db




2 Answers
2



You can achieve this creating helper function:



I will explain on example from my project:



First you need to create your helper function file



helper.js


module.exports =
userAuthenticated: function(req, res, next)
if(req.isAuthenticated())
return next();

res.redirect('/login')

;



As you can see I exported this function.



Then we are able to reach the code from it like this in other .js files:



other.js


const userAuthenticated = require('../../helpers/authentication.js');

router.all('/*', userAuthenticated, (req, res, next)=>
req.app.locals.layout = 'admin';
next();
);





i tried to use helper function but there were many different issue when created functions that contain code related to mongodb and transactions. For example, getting user info, inserting data into collection, etc and all these required writing the mongo client inside the function every time of each function.
– shubham saxena
Aug 9 at 6:12



Do you use mongoose? I strictly recommend to use this lib instead of native connection driver.



You could achieve your goal by creating mongoose connection in a separate file, then import connection instance to the file with db schema. For example:


const mongoose = require("./mongo");
const Schema = mongoose.Schema;

const User = new Schema({
name: type: String ,
password: type: String )

const UserModel = mongoose.model("User",User);
module.exports =
model: UserModel,
getById: id => UserModel.find(_id:id)



And then just import those file in the place where you want to use it:


const UserModel = require("./User");
...
UserModel.getById("someid").then(handler);





Thanks a lot, i'll try with this approach.
– shubham saxena
Aug 9 at 6:43






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS