猫鼬连接 [英] Mongoose Connection

查看:62
本文介绍了猫鼬连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.我在哪里错了?

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

推荐答案

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

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

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

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

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

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

这篇关于猫鼬连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆