mongodb - Mongo-atlas 连接:ReferenceError:未定义客户端
问题描述
尝试连接到 mongo atlas 时出现错误“ReferenceError:未定义客户端”。
控制台的错误:
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:******-@cluster0-5zvdy.mongodb.net/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));
现在保证集合在启动应用程序时按照您期望的方式定义。
推荐阅读
- typescript - 更新文档我不知道的文档ID云功能
- javascript - 我应该使用 Redux、Context 还是 hooks?以及如何实施
- laravel - 对视图和模型使用相同的目录是否重要
- css - Vuetify - 使用轮播覆盖文本关闭过渡
- javascript - 如何每隔几秒钟更改一次innerHTML
- java - Microsoft Z3 获得相关作业
- sql - How to insert csv file to postgresql using jmeter
- javascript - 在 apexchart 中更改图表的字体大小
- python - 以其他列值为条件的插补 - Titanic 数据集以类别和性别为条件的年龄插补
- ios - 如何在 xcode 11 中添加预编译头文件