我阅读了 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');
};
这是我的代码。控制台只打印
h1
,而不打印 h
。我哪里错了?
当您调用
mongoose.connect
时,它将与数据库建立连接。
但是,您在稍后的时间点(正在处理请求时)附加
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 的连接,只需在你的模块中 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);
使用单例模式的猫鼬连接
Mongoose 连接文件 - db.js
//Import the mongoose module
const mongoose = require('mongoose');
class Database { // Singleton
connection = mongoose.connection;
constructor() {
try {
this.connection
.on('open', console.info.bind(console, 'Database connection: open'))
.on('close', console.info.bind(console, 'Database connection: close'))
.on('disconnected', console.info.bind(console, 'Database connection: disconnecting'))
.on('disconnected', console.info.bind(console, 'Database connection: disconnected'))
.on('reconnected', console.info.bind(console, 'Database connection: reconnected'))
.on('fullsetup', console.info.bind(console, 'Database connection: fullsetup'))
.on('all', console.info.bind(console, 'Database connection: all'))
.on('error', console.error.bind(console, 'MongoDB connection: error:'));
} catch (error) {
console.error(error);
}
}
async connect(username, password, dbname) {
try {
await mongoose.connect(
`mongodb+srv://${username}:${password}@cluster0.2a7nn.mongodb.net/${dbname}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);
} catch (error) {
console.error(error);
}
}
async close() {
try {
await this.connection.close();
} catch (error) {
console.error(error);
}
}
}
module.exports = new Database();
从app.js调用连接
const express = require("express"); // Express Server Framework
const Database = require("./utils/db");
const app = express();
Database.connect("username", "password", "dbname");
module.exports = app;
我也出现了同样的错误。然后我发现我没有运行 mongod 来监听连接。为此,您只需打开另一个命令提示符(cmd)并运行 mongod
Mongoose 的默认连接逻辑从 4.11.0 开始已弃用。建议使用新的连接逻辑:
这是 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;
}
我建立连接的简单方法:
const 猫鼬 = require('猫鼬')
mongoose.connect(<connection string>);
mongoose.Promise = global.Promise;
mongoose.connection.on("error", error => {
console.log('Problem connection to the database'+error);
});