我在一個名為 record.js 的檔案中有以下代碼,它定義了一個 express api 的路由,并且包含在 server.js 以及服務器偵聽器 app.listen() 中。
const express = require(“express”);
const recordRoutes = express.Router();
const dbo = require(“../db/conn”);
recordRoutes.route(“/record”).get(function (req, res) {
let db_connect = dbo.getDb('mernit');
console.log(db_connect);
db_connect
.collection(“records”)
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
res.send(“hello_world");
});
此代碼是根據:https : //www.mongodb.com/languages/mern-stack-tutorial撰寫的, 但具有簡化的服務器端。
在確保服務器連接、控制臺記錄 db_connect 物件并嘗試訪問集合“記錄”后,我收到以下錯誤。
TypeError: db_connect.collection is not a function
at C:\Users\bbell\projects\MERN\server\routes\record.js:20:6
at Layer.handle [as handle_request] (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\bbell\projects\MERN\server\node_modules\express\lib\router\index.js:47:12)
錯誤拋出'.collection(“records”)'...
此外,當嘗試在 http://localhost:3000/record 上進行 GET 時,前端會回傳 HTTP 回應代碼 500。
我正在將 Mongo 4.4.10 與 Atlas 一起使用。我稍微調查了這個問題,似乎連接方法可能已在某些早期版本中被棄用或重新設計。
但是,教程(上面鏈接)如果是最新的,則表明該功能仍然有效。
有誰知道為什么我的路線無法訪問,以及如何成功訪問我的資料庫集合“記錄”?
謝謝,
布蘭登
uj5u.com熱心網友回復:
您缺少“員工”,此路線的代碼應如下所示
recordRoutes.route("/record").get(function (req, res) {
let db_connect = dbo.getDb("employees");
db_connect
.collection("records")
.find({})
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
});
});
此外,您的 res.send("hello world)線路缺少結束語。
uj5u.com熱心網友回復:
在恢復對 conn.js 檔案的一些更改并洗掉一些雜散的 res.funcs 后得到了它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366968.html
