我使用 MERN 堆栈开发宠物项目。我在 MongoDB 网站上找到了tutorial。但是有一个错误:
TypeError: Cannot read properties of undefined (reading 'collection')
并且不知道为什么。
server.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/book.js"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, () => {
// perform a database connection when server starts
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});`
config.env
ATLAS_URI=mongodb://localhost:27017/
PORT=5000
conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("ByReader");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
book.js
const express = require("express");
// recordRoutes is an instance of the express router.
// We use it to define our routes.
// The router will be added as a middleware and will take control of requests starting with path /record.
const recordRoutes = express.Router();
// This will help us connect to the database
const dbo = require("../db/conn");
// This help convert the id from string to ObjectId for the _id.
const ObjectId = require("mongodb").ObjectId;
// This section will help you get a list of all the records.
recordRoutes.route("/books").get(function (req, res) {
let db_connect = dbo.getDb();
db_connect
.collection("Books")
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
// This section will help you get a single record by id
recordRoutes.route("/book/:title").get(function (req, res) {
let db_connect = dbo.getDb();
let myquery = { title: ObjectId(req.params.title) };
db_connect
.collection("Books")
.findOne(myquery, function (err, result) {
if (err) throw err;
res.json(result);
});
});
module.exports = recordRoutes;
为了测试与数据库的连接,我在终端中写了
node server.js
。对此的响应 - ``服务器正在端口上运行:5000````。我去 localhost:5000/books 并得到错误 - TypeError: Cannot read properties of undefined (reading 'collection')
使用 npm 安装 mongoose
npm i mongoose
然后使用此代码连接到 mongodb
const {connect} = require("mongoose");
connect('mongodb://localhost:port/db-name')