node.js 猫鼬连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20360531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:25:44  来源:igfitidea点击:

Mongoose Connection

node.jsmongodbmongoose

提问by CSnerd

I read the quick start from the Mongoose websiteand I almost copy the code, but I cannot connect the MongoDB using Node.js.

我从Mongoose 网站阅读了快速入门,我几乎复制了代码,但是我无法使用 Node.js 连接 MongoDB。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

exports.test = function(req, res) {
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  console.log("h1");
  db.once('open', function callback () {
    console.log("h");
  });
  res.render('test');
};

This is my code. The console only prints h1, not h. Where am I wrong?

这是我的代码。控制台只打印h1,不打印h。我哪里错了?

回答by robertklep

When you call mongoose.connect, it will set up a connection with the database.

当您调用 时mongoose.connect,它将建立与数据库的连接。

However, you attach the event listener for openat a much later point in time (when a request is being handled), meaning that the connection is probably already active and the openevent has already been called (you just weren't yet listening for it).

但是,您open在更晚的时间点(正在处理请求时)附加事件侦听器,这意味着连接可能已经处于活动状态并且open事件已经被调用(您只是还没有侦听它) .

You should rearrange your code so that the event handler is as close (in time) to the connect call as possible:

您应该重新排列代码,以便事件处理程序尽可能接近(及时)连接调用:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log("h");
});

exports.test = function(req,res) {
  res.render('test');
};

回答by fino

The safest way to do this, it to "listen for the connect event". This way you don't care how long it takes for the DB to give you a connection.

Once that is done - you should start the server. Also.. config.MONGOOSE is exposed across your app, so you only have one DB connection.

If you want to use mongoose's connection, simply require config in your module, and call config.Mongoose. Hope this helps out someone!

Here's the code.

最安全的方法是“监听连接事件”。这样您就不必关心数据库为您提供连接需要多长时间。

完成后 - 您应该启动服务器。此外.. config.MONGOOSE 在您的应用程序中公开,因此您只有一个数据库连接。

如果你想使用 mongoose 的连接,只需在你的模块中 require config,然后调用 config.Mongoose。希望这对某人有所帮助!

这是代码。

var mongoURI;

mongoose.connection.on("open", function(ref) {
  console.log("Connected to mongo server.");
  return start_up();
});

mongoose.connection.on("error", function(err) {
  console.log("Could not connect to mongo server!");
  return console.log(err);
});

mongoURI = "mongodb://localhost/dbanme";

config.MONGOOSE = mongoose.connect(mongoURI);

回答by Zhangali Bidaibekov

I had the same error popping up. Then I found out that I didn't have a mongod running and listening for connections. To do that you just need to open another command prompt (cmd) and run mongod

我有同样的错误弹出。然后我发现我没有运行和监听连接的 mongod。为此,您只需要打开另一个命令提示符(cmd)并运行 mongod

回答by Do Async

Mongoose's default connection logic is deprecated as of 4.11.0. It is recommended to use the new connection logic:

Mongoose 的默认连接逻辑自 4.11.0 起已弃用。推荐使用新的连接逻辑:

  • useMongoClient option
  • native promise library
  • 使用MongoClient 选项
  • 原生承诺库


Here is the example from npm module: mongoose-connect-db

这是来自 npm 模块的示例:mongoose-connect-db

// Connection options
const defaultOptions = {
  // Use native promises (in driver)
  promiseLibrary: global.Promise,
  useMongoClient: true,
  // Write concern (Journal Acknowledged)
  w: 1,
  j: true
};

function connect (mongoose, dbURI, options = {}) {
  // Merge options with defaults
  const driverOptions = Object.assign(defaultOptions, options);

  // Use Promise from options (mongoose)
  mongoose.Promise = driverOptions.promiseLibrary;

  // Connect
  mongoose.connect(dbURI, driverOptions);

  // If the Node process ends, close the Mongoose connection
  process.on('SIGINT', () => {
    mongoose.connection.close(() => {
      process.exit(0);
    });
  });

  return mongoose.connection;
}

回答by todd bascombe

A simple way i make a connection:

我建立连接的一种简单方法:

const mongoose = require('mongoose')

const 猫鼬 = 要求('猫鼬')

mongoose.connect(<connection string>);
mongoose.Promise = global.Promise;
mongoose.connection.on("error", error => {
    console.log('Problem connection to the database'+error);
});