簡體   English   中英

MongoAtlas 錯誤:無效的架構,預期的 mongodb

[英]MongoAtlas Error: invalid schema, expected mongodb

我正在嘗試連接到 MongoAtlas,但是我不斷收到Error: invalid schema, expected mongodb

似乎我可以連接,但它無法從 MongoAtlas 獲取我的數據庫。 我的 try catch 錯誤返回給我(node:5964) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined

.env

PORT = 9055
MONGO_URI =mongodb+srv://<my-db-username>:<my-password>@cluster0.vossd.mongodb.net/<db-name>?
retryWrites=true&w=majority

服務器.js

require('dotenv').config();
const port = Number.parseInt(process.env.PORT, 10);
const mongoUri = process.env.MONGO_URI;

const {MongoClient} = require('mongodb');
const express = require('express');

const Application = require('./application');

const application = Application();

const Health = require('./health');
const Product = require('./product');
const Cart = require('./cart');
const Order = require('./order');

async function main() {
  let db;
  try {
    db = await MongoClient.connect(mongoUri); 
    console.log(db)
  } catch (err) {
    console.log(err);
  }

    application.use('/health', Health());
    application.use('/product', Product(db));
    application.use('/cart', Cart(db));
    application.use('/order', Order(db));
    

    const server = application.listen(port, () => {
        const host = server.address().address;
        const port = server.address().port;
        console.log(`Shopping website server up and running, listening at http://${host}:${port}`); 
      });
 }

 main();

當我連接到本地數據庫時一切正常,所以我不確定我做錯了什么。 非常感謝任何建議。 謝謝!

This cannot read property 'collection' of undefined可能會產生誤導,因為您發現了連接時發生的錯誤。 因此db為空,因此如果您訪問集合,它將出現此錯誤。 下面是來自 Mongo Atlas 的示例代碼。

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@test.w7hgn.mongodb.net/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true }); // <-- note the option
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM