MongoDB不会插入文档

0s0u357o  于 2022-12-26  发布在  Go
关注(0)|答案(1)|浏览(139)

我不知道我做错了什么,但以下是行不通的.
我有数据库连接,但当我尝试使用连接,它不会让我。
index.js

config = require('./config');
const express = require('express');
const app = express();
const mDB = require('./components/mongodb').connect(config.dbUri);
app.get('/testDB', (req,res) =>{
  const user = { name: 'John', age: 30 };

  mDB.insertOne(user, (error, result) => {
    if (error) {
      console.log(error);
      return;
    }
    console.log(`Successfully inserted user: ${result.insertedId}`);
    res.send("inserted");
  });

});

app.listen(3000, () => {
  console.log('App listening on port 3000');
});

./components/mongodb.js

const MongoClient = require('mongodb').MongoClient;

module.exports.connect = (uri) => {
  MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
    if (err) {
      console.error(`MongoDB connection error: ${err}`);
      process.exit(1);
    }

    console.log('Successfully connected to MongoDB');
    module.exports.client = client;
  });
};

module.exports.insertOne = (collection, document) => {
  module.exports.client.db('PodToo').collection(collection).insertOne(document, (error, result) => {
    if (error) {
      console.log(error);
      return;
    }
    console.log(`Successfully inserted document: ${result.insertedId}`);
  });
};

我得到了Successfully connected to MongoDB
但当我尝试使用它时

TypeError: Cannot read properties of undefined (reading 'insertOne')
flvlnr44

flvlnr441#

冒着说出明显事实的危险:您缺少insertOne函数的第一个参数,即集合名称。
你是说

mDB.insertOne('users', user, ...

相关问题