当我尝试连接到mongo地图集时,我收到错误“ReferenceError:client is not defined”。
控制台的错误:
const db = client.db('coneccao-teste'); ReferenceError:未定义客户端
请参阅下面的NodeJs代码以及Express服务器和mongo-atlas连接的配置。
有你的建议吗?
谢谢!
const express = require('express');
const app = express();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const port = 3000;
const mongo_uri = 'mongodb+srv://rbk:******[email protected]/coneccao-teste?retryWrites=true';
const db = client.db('coneccao-teste');
const collection = db.collection('inicio');
MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
const db = client.db('coneccao-teste');
const collection = db.collection('inicio');
app.listen(port, () => console.info(`REST API running on port ${port}`));
}).catch(error => console.error(error));
// add this line before app.listen()
app.locals.collection = collection;
app.get('/', (req, res) => {
const collection = req.app.locals.collection;
collection.find({}).toArray().then(response => res.status(200).json(response)).catch(error => console.error(error));
});
app.get('/:id', (req, res) => {
const collection = req.app.locals.collection;
const id = new ObjectId(req.params.id);
collection.findOne({ _id: id }).then(response => res.status(200).json(response)).catch(error => console.error(error));
});
app.listen(port);
关于你的第二个问题,集合没有定义。
当你声明:
app.locals.collection = collection;
您的mongo连接可能尚未连接,这意味着此时集合未定义
在建立连接之后和开始使用您的应用程序之前插入此声明:
MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
const db = client.db('coneccao-teste');
const collection = db.collection('inicio');
app.locals.collection = collection;
app.listen(port, () => console.info(`REST API running on port ${port}`));
}).catch(error => console.error(error));
现在,该集合保证按照您在启动应用程序时的预期方式进行定义。