Mongo-atlas connection : ReferenceError: client is not defined

Mongo-atlas connection : ReferenceError: client is not defined

尝试连接到 mongo 地图集时出现错误 "ReferenceError: client is not defined"。

Console's erro :

const db = client.db('coneccao-teste'); ReferenceError: client is not defined

请参阅下面我的 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));

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