const express = require("express");
const bodyParser = require("body-parser");
const { MongoClient } = require("mongodb");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
const uri =
"mongodb+srv://username:1234321@cluster0.8imjcky.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run() {
try {
const todolistDB = client.db("todolistDB");
const dbItem = todolistDB.collection("Item");
const defaultItems = [
{ item1: "welcome to your todolist" },
{ item2: "add new Item"},
{ item3: "delete item"}
];
const result = await dbItem.insertMany(defaultItems);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
run().catch(console.dir);
app.get("/", function(req, res) {
//const dbItem = app.locals.collection;
dbItem.find({}, function(err, foundItems){
res.render("list", {listTitle: "Today", newListItems: foundItems});
});
这是我编写的连接到我的Mongo Atlas的代码。应用程序连接到Atlas,并且已经在Atlas中创建了dbItem数据库。
然而,当尝试我的运行服务器在终端中出现此错误:第一个月
我也试过在app.get
函数之前使用app.locals.collections = dbItem
,但效果不佳。
1条答案
按热度按时间zd287kbt1#
dbItem
仅在创建它的作用域中。在这种情况下,它是运行函数。当该函数返回时,dbItem
福尔斯作用域并被垃圾收集。您可以尝试在与
client
相同的位置声明todolist
和dbItem