当尝试连接到mongo地图集时,出现错误“ 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);
答案 0 :(得分:0)
关于第二个问题,集合没有定义。
当您声明:
app.locals.collection = collection;
您的mongo连接可能尚未连接,这意味着该集合当时未定义
在建立连接之后并且在开始使用ur app监听之前插入以下声明:
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));
现在确保可以按照启动应用程序时的预期方式定义集合。