mongoose连接

我读了这个网站的快速入门链接 ,我几乎复制了代码,但是我无法使用nodejs连接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'); }; 

这是我的代码。 控制台可以打印(h1)不是(h),我错在哪里?

当你调用mongoose.connect ,它将build立与数据库的连接。

但是,您将在稍后的时间点(在处理请求时)附加事件侦听器以便open ,这意味着连接可能已经处于活动状态,并且已经调用了open事件(您刚刚还没有侦听它)。

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

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

最安全的方法就是“听连接事件”。 这样你就不用关心数据库给你连接需要多长时间。

一旦完成 – 你应该启动服务器。 另外.. config.MONGOOSE暴露在您的应用程序,所以你只有一个数据库连接。

如果你想使用mongoose的连接,只需要在你的模块configuration,并调用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); 

我popup同样的错误。 然后我发现我没有运行Mongo并且正在监听连接。 要做到这一点,你只需要打开另一个命令提示符(cmd)并运行mongod

Mongoose的默认连接逻辑从4.11.0开始已弃用。 build议使用新的连接逻辑:

  • 使用MongoClient选项
  • 本地承诺库

这里是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; }