RethinkDB,ReferenceError:未定义连接

时间:2017-01-05 21:25:01

标签: javascript node.js express rethinkdb

我正在使用Express.jsRethink,我正在尝试对一条将一些信息保存到数据库的路由做一个简单的post。初始连接正常工作并记录到然而,当我尝试使用与Connected to Rethink的连接时,我一直收到ReferenceError: connection is not defined。这是代码:

insert

1 个答案:

答案 0 :(得分:1)

这是一个范围问题。连接在本地范围内,您尝试访问它,就像它是全局的一样。变化:

var express = require('express');
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt = require('bcryptjs');

function dbConnect(){
  var connection = null;
  r.connect({host: 'localhost', port: 28015}, function(err, conn){
    if (err){
      throw err;
    }else{
      connection = conn;
      console.log("Connected to Rethink");
    }
  });
}`

var express = require('express');
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt = require('bcryptjs');
var connection = null;
function dbConnect(){

  r.connect({host: 'localhost', port: 28015}, function(err, conn){
    if (err){
      throw err;
    }else{
      connection = conn;
      console.log("Connected to Rethink");
    }
  });
}