【问题标题】:"MongoError: Topology is closed" error in EJSEJS 中的“MongoError:拓扑已关闭”错误
【发布时间】:2020-09-16 23:44:01
【问题描述】:

好的,所以我创建了一个 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

【问题讨论】:

  • 尝试将useUnifiedTopology设置为false
  • 不,那没用
  • 我遇到了同样的问题并以某种方式解决了,但不记得如何了。您是尝试连接本地数据库还是连接到云端
  • 我正在尝试连接到云(atlas)并且我已将动态 ip (0.0.0.0/0) 列入白名单

标签: javascript node.js mongodb express ejs


【解决方案1】:

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

实际上建议不要一次又一次地调用client.connect。所以我想出的解决方案是我们在服务器启动时调用client.connect()然后根本不会关闭它。访问数据库,只需将客户端作为函数中的变量传递,就像这样-

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

}

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 2021-06-21
    • 2020-05-13
    • 2015-09-03
    • 2015-07-09
    • 2020-10-23
    • 2016-12-27
    相关资源
    最近更新 更多