0

okay so I've made a profile.ejs page,I get the following error when I reload the page.Can someone explain me whats happening.Ive attached all my code below.I am using node js and express as a server.I read this post but didnt understand whats happening.It would be grat if someone could explain the reason for the error .thanks.

profile.ejs

   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="Stylesheet" href="../addmie/css/styles.css">
    <link >
    <script src="../addmie/js/loadprofile.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <title>Document</title>
</head>
<body>
    <%- include('header.ejs')%>
    <%var postlink="/sendpost/"+userobj.username; %>
    <div class="grid-container">
        <div class="grid-container-left">
            <div class="profile">
                <div id="profile_picture">this feature is not yet available</div>
                <div id="username"><%=userobj.username%></div>
            </div>
            <div class="container">
                <h1>friends</h1>
                <div id="friends-container">
                    <ul>
                        <%for(i=0;i< userobj.friends.length;i++){%>
                            <li><%- include('friends.ejs',{friend:userobj.friends[i]})%></li>
                        <%}%>
                    </ul>
                </div>                
            </div>
        </div>
        <div class="grid-container-right">
            <div class="postform">


                <form  method="POST" action=<%=postlink%> >
                    <input type='text' name='text' value='Write Something Here'/>
                    <input id='post' type='submit' name='post' value='Post'/>
                </form>
            </div>
            <div class="post-container">
                <h1>your posts</h1>
                <ul>
                    <%for(i=0;i< postobj.length;i++){%>
                        <li><%-include('mypostcontainer.js',{postobj:postobj[i]});%></li>
                    <%}%>
                </ul>

            </div>
        </div>
    </div>
</body>
</html>

fetch.js

const MongoClient = require('mongodb').MongoClient;
const uri = "somelink";
const client = new MongoClient(uri, {useUnifiedTopology:true}); 
var result=null;
var posts=null;
module.exports = async function dbconnect(from,res)
{   
       try {
        // Connect to the MongoDB cluster
        await client.connect();
        console.log('client connected sucessfully');
        // Make the appropriate DB calls
        result=await client.db('profile').collection('user').findOne({username:from});
        posts=await client.db('profile').collection('post').find({username:from}).toArray();
        //console.log(result);
        //console.log(posts);
    } catch (e) {
        console.log('error connecting to db');
        console.error(e);
        res.render('addmie.ejs')
    } finally {
        console.log('closing client connection');
        await client.close();
        console.log(posts);
        res.render('profile.ejs',{userobj:result,postobj:posts});
    }

}

controller.js

app.get('/profile/:username',function(req,res){
        console.log('get request to profile');
        var userobj={
            username:req.params.username,
        };
        let fetch=require('../dbconnect/fetch.js');
        const fname=null;
        fetch(req.params.username,res);
        console.log('profile loaded');

    });

error

MongoError: Topology is closed, please connect
    at processWaitQueue (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\sdam\topology.js:998:42)
    at NativeTopology.selectServer (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\sdam\topology.js:440:5)
    at executeWithServerSelection (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\operations\execute_operation.js:137:12)
    at executeOperation (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\operations\execute_operation.js:75:7)
    at Cursor._initializeCursor (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:536:7)
    at Cursor._initializeCursor (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\cursor.js:185:11)
    at nextFunction (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:739:10)
    at Cursor._next (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:202:5)
    at C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\cursor.js:248:14
    at maybePromise (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\utils.js:719:3) {   [Symbol(mongoErrorContextSymbol)]: {} } Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:1008:10)
    at tryHandleCache (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\ejs\lib\ejs.js:278:5)
    at View.exports.renderFile [as engine] (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\ejs\lib\ejs.js:489:10)
    at View.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:1012:7) get request to profile the options [servers] is not supported the options [caseTranslate] is not supported the options [dbName] is not supported the options [srvHost] is not supported the options [credentials] is not supported the options [username] is not supported the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,keepAliveInitialDelay,connectTimeoutMS,family,socketTimeoutMS,reconnectTries,recon nectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bufferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,p romoteValues,promoteBuffers,promoteLongs,domainsEnabled,checkServerIdentity,validateOptions,appname,auth,user,password,authMechanism,compression,fsync,readPreferenceTags,numberOfRetries,auto_reconnect,minSize,monitorCommands,retryWrites,retryReads,useNewUrlParser,useUnifiedTopology,serverSelectionTi meoutMS,useRecoveryToken,autoEncryption,driverInfo,tls,tlsInsecure,tlsinsecure,tlsAllowInvalidCertificates,tlsAllowInvalidHostnames,tlsCAFile,tlsCertificateFile,tlsCertificateKeyFile,tlsCertificateKeyFilePassword,minHeartbeatFrequencyMS,heartbeatFrequencyMS,waitQueueTimeoutMS] the options [mode] is not supported the options [tags] is not supported the options [preference] is not supported the options [isValid] is not supported the options [slaveOk] is not supported the options [equals] is not supported the options [toJSON] is not supported the options [source] is not supported the options [mechanism] is not supported the options [mechanismProperties] is not supported
Mike Doe
  • 16,349
  • 11
  • 65
  • 88
Nikhil Singh
  • 353
  • 1
  • 17

1 Answers1

0

I have found a solution to this problem,look at this link

Actually it is recommended to not call client.connect again and again.so the solution Ive figured out is we call client.connect() when the server starts and then won't close it at all.to access the db,just pass the client as a variable in function like so-

module.exports = async function dbconnect(from,res,client)
{   
       try {
        // Connect to the MongoDB cluster
        //await client.connect();
        console.log('client connected sucessfully');
        // Make the appropriate DB calls
        result=await client.db('profile').collection('user').findOne({username:from});
        posts=await client.db('profile').collection('post').find({username:from}).toArray();
        //console.log(result);
        //console.log(posts);
    } catch (e) {
        console.log('error connecting to db');
        console.error(e);
        await res.render('addmie.ejs')
    } finally {
        console.log('closing client connection');
        //await client.close();
        console.log(posts);
        await res.render('profile.ejs',{userobj:result,postobj:posts});
    }

}
Nikhil Singh
  • 353
  • 1
  • 17