我不知道我做错了什么,但以下是行不通的.
我有数据库连接,但当我尝试使用连接,它不会让我。
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')
1条答案
按热度按时间flvlnr441#
冒着说出明显事实的危险:您缺少insertOne函数的第一个参数,即集合名称。
你是说
?