猫鼬连接 [英] Mongoose Connection
问题描述
我从 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屋!