这个问题在这里是密切相关的,但问题和答案根本不是很相关。但是,在该 OP 帖子的评论中,使用 .close() 存在困难......这就是相似之处的结束。
问题来自尝试使用直接 nodejs mongodb 驱动程序 3.9 创建 api。我在控制器中有客户端调用,因为将它放在服务器中并在需要时调用客户端会不断产生“连接错误”,所以这里它在控制器中以获得完整的上下文。
每当我在集合客户端调用中使用 .close() 时,它都会运行一次,然后之后的所有其他调用都会导致错误拓扑已关闭。所以,现在我把它注释掉了。我想知道是什么原因造成的,我做错了什么会导致这个错误?
每个驱动程序的文档说明使用它以及目的是什么,但它反复破坏了我的 api。
const express = require('express');
const router = express.Router();
import { MongoClient, MongoCallback, MongoError, MongoNetworkError } from 'node_modules/mongodb';
// const MongoClient = require('node_modules/mongodb').MongoClient;
const dbName = 'HealthCheckup';
const documentName = 'userProfile';
const assert = require('assert');
const url = `mongodb+srv://UserDB:h7srvvvvvvvHFd8@vvvvvvvvvai-cvyrh.azure.mongodb.net/${dbName}?retryWrites=true&w=majority`;
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true});
const findUsers = (client, callback) => {
// Get the documents collection
const collection = client.collection(documentName);
// Insert some documents
collection.find({}).toArray( (err, result) => {
// console.log('err **** -------- ', err);
// console.log('Result -------- ', result);
callback(err, result);
});
}
const createUser = (client, callback, req) => {
// Get the documents collection
const collection = client.collection(documentName);
// Insert some documents
collection.insertOne({
name: req.body.name,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
tokenId: req.body.tokenId,
userPhoto: req.body.userPhoto
}, (err, result) => {
// console.log('err **** -------- ', err);
// console.log('Result -------- ', result);
callback(err, result);
});
}
// localhost:4021/user
router.get('/', (req, res) => {
client.connect( err => {
const collection = client.db(dbName);
if (!err) {
console.log("Connected successfully to server.");
} else {
console.log('Error in DB connection : ', JSON.stringify(err, undefined, 2));
}
findUsers(collection, (err, result) => {
console.log('err 2222222 -------- ', err);
console.log('Result 2222222 -------- ', result);
if (!err) {
res.send(result);
} else {
console.log('Error retreiving user ', JSON.stringify(err, undefined, 2))
}
console.log('BREAKPOINT 00000000000000000');
// client.close();
});
});
});