Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 节点js未定义的mongodb连接_Javascript_Node.js_Mongodb - Fatal编程技术网

Javascript 节点js未定义的mongodb连接

Javascript 节点js未定义的mongodb连接,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我有3个文件 /custom/db.js用于连接到mongodb的数据库 const mongodb= require('mongodb'); var mongoclient= require('mongodb').MongoClient; var dburl1= 'mongodb://localhost:27017'; var _db; function dbconn(){ var _db; async function books(){ a

我有3个文件

/custom/db.js用于连接到mongodb的数据库

const mongodb= require('mongodb');
var mongoclient= require('mongodb').MongoClient;
var dburl1= 'mongodb://localhost:27017';
var _db;

    function dbconn(){
      var _db;
      async function books(){

        await mongoclient.connect(dburl1, {keepAlive: 30000, connectTimeoutMS: 30000, useUnifiedTopology: true }, (err, db)=>{
          dbo=  db.db('books');
          _db= dbo; 
         
        })
        return _db;
      }
      return {
        books: books, 
      }
    }
module.exports= dbconn();
/custom/ctrg.js从mongodb获取数据

async function books_by_ctrg(ctrg, limit, start) {
        console.log(ctrg);
    if(start == null) start=0;

        const dbo = await  db.books();

        // console.log(dbo);
        await dbo.collection('books1').find({}).skip(start).limit(limit).toArray((err, result)=>{if(err){console.log(err); return err;}else{data= result;}})
    
        return data;
};
/router/home.js路由器文件(将Express与EJS一起使用)

这些都是上面的文件,用于从数据库中获取主页数据

问题

第一次加载时我犯了这个错误

node:6536) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined
    at Object.books_by_ctrg [as get_book_ctrg] (C:\node\custom\ctrg.js:15:19)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async C:\node\routes\home.js:12:15
(node:6536) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6536) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
在第二次加载时(这意味着数据库连接现在正在工作“没有文件更改,只是在浏览器中刷新”)

TypeError:C:\node\views\home.ejs:67
65|         
66|
>> 67|     { %>
68|         
69|             
70|                 
无法读取未定义的属性“forEach”
评估时(编译时评估)(C:\node\node\u modules\ejs\lib\ejs.js:662:12),:14:13)
在家(C:\node\node\u modules\ejs\lib\ejs.js:692:17)
在tryHandleCache(C:\node\node\u modules\ejs\lib\ejs.js:272:36)
在View.exports.renderFile[作为引擎](C:\node\node\u modules\ejs\lib\ejs.js:489:10)
在View.render(C:\node\node\u modules\express\lib\View.js:135:8)
在tryRender(C:\node\node\u modules\express\lib\application.js:640:10)
位于Function.render(C:\node\node\u modules\express\lib\application.js:592:3)
在ServerResponse.render(C:\node\node\u modules\express\lib\response.js:1012:7)
在C:\node\routes\home.js:20:9
在处理和拒绝时(内部/process/task_queues.js:97:5)

在这两次访问或刷新之后(一切正常无错误无警告一切都很完美)

错误已经告诉了你很多

TypeError:无法读取未定义的属性“collection”

这意味着当您调用
wait dbo.collection('books1')
时,
dbo
变量是
undefined
。这告诉我们
db.books();
不会返回您需要的实例。因此问题在于
/custom/db.js
文件

在该文件中有几个问题

var _db; // <-- 1st definition of _db (it's not wrong, but just confusing).

function dbconn(){
  var _db; // <-- 2nd definition of _db (this should be the only definition).
  async function books(){

    // Because you use a callback, no promise is returned, therefor it will not await.
    // @see http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#.connect
    await mongoclient.connect(dburl1, {keepAlive: 30000, connectTimeoutMS: 30000, useUnifiedTopology: true }, (err, db)=>{
      dbo=  db.db('books'); // <-- dbo is never defined
      _db= dbo; //
    })

    // _db will still be undefined because await didn't work.
    // This will cause the error.
    return _db;
  }
  
  return {
    books: books, 
  }
}

nodejs:v12.16.3,MongoDb:v5.x.xMaybe这不是问题,当我刷新页面时,相同的脚本可以正常运行。第一次页面加载返回的Dbo undefined不是第二次那么好,第一次
\u db
将是未定义的,但是
mongoclient.connect
在它有b之后仍然会更新全局
\u db
变量甚至返回。这意味着第二次返回
\u db
时,它将不再是未定义的,并且有一个
db
实例。这个答案将解决这个问题。你能解释一下为什么它在第二次加载或刷新时工作正常。非常感谢你指出同样的问题,我已经修复了我的ctrg.js文件,现在就做所有的事情非常好。
TypeError: C:\node\views\home.ejs:67
    65|         <div class="course-slider owl-carousel">
    66|
 >> 67|     <% data.forEach(book=>{ %>
    68|         <a href="<%= book.link %>">
    69|             <div class="course-item">
    70|                 <figure class="course-preview">

Cannot read property 'forEach' of undefined
    at eval (eval at compile (C:\node\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:14:13)
    at home (C:\node\node_modules\ejs\lib\ejs.js:692:17)
    at tryHandleCache (C:\node\node_modules\ejs\lib\ejs.js:272:36)
    at View.exports.renderFile [as engine] (C:\node\node_modules\ejs\lib\ejs.js:489:10)
    at View.render (C:\node\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\node\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\node\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\node\node_modules\express\lib\response.js:1012:7)
    at C:\node\routes\home.js:20:9
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
var _db; // <-- 1st definition of _db (it's not wrong, but just confusing).

function dbconn(){
  var _db; // <-- 2nd definition of _db (this should be the only definition).
  async function books(){

    // Because you use a callback, no promise is returned, therefor it will not await.
    // @see http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#.connect
    await mongoclient.connect(dburl1, {keepAlive: 30000, connectTimeoutMS: 30000, useUnifiedTopology: true }, (err, db)=>{
      dbo=  db.db('books'); // <-- dbo is never defined
      _db= dbo; //
    })

    // _db will still be undefined because await didn't work.
    // This will cause the error.
    return _db;
  }
  
  return {
    books: books, 
  }
}
const { MongoClient } = require("mongodb");
const dburl1 = "mongodb://localhost:27017";

function dbconn() {
  const mongoclient = new MongoClient(dburl1, {
    connectTimeoutMS: 30000,
    useUnifiedTopology: true
  });

  async function books() {
    try {
      await mongoclient.connect();
      return mongoclient.db("books");
    } catch(error) {
      console.error(error);
    } finally {
      await client.close();
    }
  }

  return {
    books
  };
}

module.exports = dbconn();