简体   繁体   English

如何将连接结果保存到nodeJs中的变量中

[英]How to save connection result in a variable in nodeJs

I'm trying to save a function return in a const because I would be able to use informations outside of the function. 我试图将函数返回值保存在const中,因为我将能够使用函数外部的信息。 To illustrate more my problem here's a piece of code. 为了进一步说明我的问题,这里有一段代码。

const express = require('express')
const app = express()
var routes = require('./routes/routes');
var bodyParser = require('body-parser')
var MongoClient = require('mongodb').MongoClient;
const dbb = MongoClient.connect("mongodb://user:tpassword@ds137600.mlab.com:37600/tasksdb", { useNewUrlParser: true }, function (err, db) {
    if (!err) {
        console.log(db.db().databaseName);
    }
    else {
        console.log(err)
    }
});
app.use('/', routes);
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000, function () {
    console.log("second", dbb);

    console.log('Example app listening on port 3000!')
})

Here's what I get in terminal : 这是我在终端中得到的:

second undefined
Example app listening on port 3000!
tasksdb

How can I get db information outside of MongoClient.connect function so that I could pass them to routes module ? 我如何在MongoClient.connect函数之外获取数据库信息,以便将它们传递给路由模块?

Firstly be careful while copy pasting code on a platform,remove passwords if any in the code, infact mongoURL should be in .env file not in the main js. 首先,在平台上复制粘贴代码时要小心,删除代码中的密码(如果有的话),实际上mongoURL应该在.env文件中而不是在主要js中。

MongoClient.connect() is an asynchronous call, therefore when the line MongoClient.connect()是一个异步调用,因此当行

console.log("second", dbb);

is executed, MongoClient.connect() is still pending 执行后,MongoClient.connect()仍处于待处理状态

To make it synchronous there are multiple solutions: 为了使其同步,有多种解决方案:

MAKE USE OF THE CALLBACK 利用回调

const dbb = MongoClient.connect("mongodb://user:tpassword@ds137600.mlab.com:37600/tasksdb", { useNewUrlParser: true }, function (err, db) {
    if (!err) {
        console.log(db.db().databaseName);
    app.listen(3000, function () {
    console.log("second", dbb);

    console.log('Example app listening on port 3000!')
})
    }
    else {
        console.log(err)
    }
});

now the console.log will only be executed when the mongoose.connect has finished 现在console.log仅在mongoose.connect完成后才会执行

ASYNC AWAIT if you have nodejs >= 7.10.1 , your nodejs support Async await , you can check here ASYNC AWAIT如果您的nodejs> = 7.10.1,则您的nodejs支持Async await,您可以在此处检查

(async function init() {
  const dbb = await MongoClient.connect("mongodb://user:tpassword@ds137600.mlab.com:37600/tasksdb", {
    useNewUrlParser: true
  });

  if(dbb){
  app.use('/', routes);
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.listen(3000, function() {
    console.log("second", dbb);

    console.log('Example app listening on port 3000!')
  })
}
})();

this solution is more readable. 该解决方案更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在循环中保存变量的结果 - How to save the result of a variable in a loop 如何在Node.js中提供文件之前保存变量 - How to save a variable before serving a file in nodejs 如何将数据从JSON保存到NodeJS中的变量 - How to save data from JSON to a variable in NodeJS 如何将MySQL搜索结果保存在变量中 - How to save mysql search result in variable 如果数据来自 Javascript,如何使用 nodejs 将数据保存在 DB 中? - How to save data in DB using nodejs if data is coming as result in Javascript? 我想从mysql的connection.query中取出结果并将其保存在nodejs中的全局scope链中 - I want to take out the result from mysql's connection.query and save it in global scope chain in nodejs 如何保存到状态并保存到获取API的本地变量结果 - how save to state and save to local variable result from fetch api 如何将数组中每个元素的结果推送到javascript nodejs中的全局变量? - how to push the result of each element in an array to a global variable in javascript nodejs? 如何将数组保存到文件中,然后再将其读入nodejs / JavaScript中的数组变量中? - How to save an array to file and later read it into an array variable in nodejs/JavaScript? 如何将 mongodb findone 值保存到 javascript 变量以便稍后在 nodejs 上使用 - How to save mongodb findone value to a javascript variable to use it later on nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM