EJS中的“ MongoError:拓扑已关闭”错误

问题描述 投票:0回答:1

好,所以我创建了一个profile.ejs页面,重新加载页面时出现以下错误。有人可以解释我发生了什么。我在下面附加了所有代码。我正在使用节点js并表示为服务器。我读了this帖子,但不了解发生了什么。如果有人可以解释该错误的原因,将不胜感激。

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');

    });

错误

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
javascript node.js mongodb express ejs
1个回答
0
投票

我已经找到了解决此问题的方法,请看此link

实际上,建议不要一次又一次地调用client.connect。因此,我发现的解决方案是,当服务器启动时我们调用client.connect(),然后根本不关闭它。只是访问数据库将客户端作为变量传递给函数,例如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});
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.