Я пытаюсь подключиться к базе данных mongodb и получаю ошибку, как показано ниже.
Это дает мне ошибку
TypeError: Cannot read properties of undefined (reading 'collection')
at C:\Users\Joh\Desktop\chipsproject\server\server.js:22:14
at Layer.handle [as handle_request] (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\route.js:149:13)
at Route.dispatch (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\route.js:119:3)
at Layer.handle [as handle_request] (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\index.js:280:10)
at cors (C:\Users\Joh\Desktop\chipsproject\server\node_modules\cors\lib\index.js:188:7)
at C:\Users\Joh\Desktop\chipsproject\server\node_modules\cors\lib\index.js:224:17
мой файл подключения выглядит следующим образом
const Express = require('express')
const app = Express()
const cors = require('cors')
app.use(cors());
const MongoClient = require('mongodb').MongoClient
var database;
app.listen(5000, ()=>{
MongoClient.connect('mongodb://localhost:27017/chips', (err, client)=>{
database=client.db('chips');
console.info('connected to database');
})
})
app.get('/user',(request,response)=>{
database.collection('users').find({}).toArray((err,results)=>{
if (err) throw err
response.send(results);
})
})
спасибо, я буду признателен за ваш ответ
🤔 А знаете ли вы, что...
С помощью JavaScript можно валидировать данные на стороне клиента, что улучшает пользовательский опыт.
Ошибка типа: невозможно прочитать свойства неопределенного значения (чтение «коллекции»)
Проблема в том, что к вашей переменной database
осуществляется доступ до ее инициализации. Это происходит потому, что соединение с MongoDB
является асинхронным, и ваш сервер может обрабатывать запросы до того, как будет установлено соединение с базой данных.
Попробуйте это вместо databse-connection
.
let database;
MongoClient.connect('mongodb://localhost:27017/chips')
.then(client => {
database = client.db('chips'); // you can also use this "client.db();"
console.info('Connected to database');
// Start the server only after successful DB connection
app.listen(5000, () => {
console.info('Server is running on port 5000');
});
})
.catch(err => console.error(err));
После этого вы можете выполнить остальную часть операции с базой данных в соответствии с вашими потребностями.
Попробуйте это, это сработает.
Предположение :-
Вы когда-нибудь задумывались над тем, что если вам понадобится экземпляр database
для другого модуля, как бы вы это сделали?
--> Хотя это мое предложение, а не фиксированное правило, вам следует определить database-connection
в отдельный модуль и, в зависимости от ваших потребностей, импортировать его в другой модуль.
Чтобы узнать, как это сделать, перейдите по ссылке ниже, где я ответил на вопрос.
https://stackoverflow.com/a/78689128/21210375