首页 > 解决方案 > 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);

标签: mongodbmongodb-atlas

解决方案


关于你的第二个问题,集合只是没有定义。

当您声明:

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));

现在保证集合在启动应用程序时按照您期望的方式定义。


推荐阅读