mongodb.当尝试连接mongodb时,connect不是函数

oxalkeyp  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(169)

第一次使用mongodb,我得到“mongodb.connect不是一个函数”当试图运行,我做错了什么?

代码:

let express = require('express')
let mongodb = require('mongodb')

let app = express()
let db

let connectionString = '...' 
mongodb.connect(connectionString, {useNewUrlParser: true}, function(err, client) {
  db = client.db()
  app.listen(3000)
})
tf7tbtn2

tf7tbtn21#

你需要使用MongoClient来连接,而且回调语法似乎表现得很奇怪,最好使用async await来连接:

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

const app = express();

app.use(express.json());
app.use(cors());

let db;

const url = 'mongodb+srv://';
const dbName = 'dbname';
const client = new MongoClient(url);

(async () => {
    db = (await client.connect()).db(dbName);
    console.log("conected!!");
})();

app.get("/someroute", async (req, res) => {
    try {
        const result = await db.collection("yourcollection").findOne({ _id: new ObjectId(req.params.id) });
        res.json(result)
    } catch (error) {
        res.status(500).json("Problem");
    }
});

app.listen(3000, () => {
    console.log("Server UP");
})

相关问题