我已经通过此链接实现了以下代码:
What is best way to handle global connection of Mongodb in NodeJs
创建用于连接MongoDB的类。但是,当我尝试在路由器中调用单例类时,出现以下错误:
TypeError:Connection.db.collection不是函数
mongodb.js
const MongoClient = require('mongodb').MongoClient
const url = '...';
class Connection {
static connectToDB() {
if ( this.database ) return Promise.resolve(this.database)
return MongoClient.connect(this.url, {useNewUrlParser: true}, (err, db) => {
if (err) console.log(err);
else {
this.db = db;
console.log('MongoDB connected');
}
})
}
}
Connection.db = null
Connection.url = url
Connection.options = {
bufferMaxEntries: 0,
reconnectTries: 5000,
}
module.exports = Connection;
app.js
const express = require('express');
const app = express();
let bodyParser = require('body-parser')
// mongodb config
const Connection = require('../config/mongodb');
const server = app.listen(3000, () => {
Connection.connectToDB(); // output: MongoDB connected
console.log(`listening to port: ${port} on http://127.0.0.1:3000}/`); // output: listening to port: 3000 on http://127.0.0.1:3000/
});
router.js
const router = require('express').Router();
let Connection = require('../config/mongodb');
router.post('/data', (req, res) => {
Connection.db.collection('tweets').find({}) // output: TypeError: Connection.db.collection is not a function
.then(tweets => console.log(tweets))
.catch(err => console.log(err));
});
答案 0 :(得分:0)
您链接的问题始终使用promise,而您使用的是connect的回调版本。
return MongoClient.connect(this.url, {useNewUrlParser: true}, (err, db) => ...
然后您可以调用此方法而无需返回服务器:
Connection.connectToDB();
console.log(`listening to port: ${port} on http://127.0.0.1:3000}/`);
因此,不能保证在您的第一个api请求进入时就已经建立了连接。实际上,如果您这样做了:
Connection.connectToDB();
console.log(`listening to port: ${port} on http://127.0.0.1:3000}/`);
Connection.db.collection('tweets').find({});
由于Connection.db仍然为null,因此每次都会失败。
在您链接的示例中,使用Promises可以防止这种情况。请特别注意connect方法:
static connectToDB() {
if ( this.database ) return Promise.resolve(this.database)
// ** USING THE PROMISE VERSION OF CONNECT **
return MongoClient.connect(this.url, this.options)
.then(db => this.db = db)
}
,您的使用代码也应使用promise:
return Connection.connectToDB()
.then(() => {
// do something here
});
答案 1 :(得分:0)
尝试一次package.json,将mongodb行更改为“ mongodb”:“ ^ 2.2.33”。您将需要npm卸载mongodb;然后npm install安装此版本。