How Could I Write a helper function which is query from mongodb , and then can call this func for any ejs template

Viewed 499

I want to write a function with one param id for this mongo to pass to my home.ejs.

Example with this query:

db.getCollection('users').find('5da85558886aee13e4e7f044', {image: 1})

Example I have a route.

routes/users.js

var User = require("../models/user");
var db = require("../secure/db");
var middleware = require("../middlewares/middleware");
 //...
router.get("/home", middleware.isAllowed, function(req, res, next) {
 res.render('home',{
  title: "Project",
  userList: userList,
  getUserimage: getUserimage(??)//trying here 
 })

});

so in home.ejs or any file.ejs I can call like getUserimage('5da85558886aee13e4e7f044') inside loop of list of ids

views/home.ejs

 <% layout('layout/layout') %>
 //more code
 <% for(var i=0; i < userList.length; i++){ %>
    <div>
    <img src ="<%=getUserimage(userList[i].id)%>" > <%=userList[i].name%> 
    </div>
 <% } %>
 //more code

Here is my updated helper

var User = require("../models/user");
var ObjectId = require('mongodb').ObjectID;

module.exports.getUserImage = async function getUserImage(id) {
  let result = await  User.find(ObjectId(id), {image: 1, _id: 0}).lean();
   console.log(result[0].image);
    return result[0].image; //or whatever you wanna return 
  };

When I console.log it is gave me the correct result. but when I call in view.ejs like this <%=getUserImage("5d999578aeb073247de4bd6e")%> file it give me [object Promise]

1 Answers

Create a file , we name it helper.js.

module.exports.getUserimage = async function(id){

    //do something
    //replace this with your own code but use the await
    let result = await collection.findOne(query);
    return result; //or whatever you wanna return 


}

Then inside app.js you can do this

const helper = require("helper");

app.locals.getUserimage = helper.getUserimage

Then you can call it inside your .ejs template like the way you are doing.

 <% layout('layout/layout') %>
 //more code
 <% for(var i=0; i < userList.length; i++){ %>
    <div>
    <img src ="<%= getUserimage(userList[i].id)%>" > <%=userList[i].name%> 
    </div>
 <% } %>
 //more code

app.locals properties persist throughout the life of the application. Provide the complete path to the helper.js file. I have assumed that is in the same directory as the app.js file.

Related