簡體   English   中英

從 mongoDB 集合中獲取數據到 ejs

[英]Get data from mongoDB collection to ejs

我正在學習如何使用 MongoDB 地圖集。 我將數據庫與我的節點應用程序連接起來,並且還可以向其中添加數據。 我面臨的唯一問題是 ejs。 我無法從我的集合中檢索我的文件路徑和標題,即使我能夠記錄我的集合中的所有數據,但我被困在如何從我的集合中獲取標題和文件路徑並使用我前面的數據-結尾。 這是我的代碼:

應用程序.js:

mongoose.connect(
  "mongodb+srv://<name>:<password>t@cluster0.cqqda.mongodb.net/proDB?retryWrites=true&w=majority"
);

const connectionParams = {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
};

mongoose.set("useCreateIndex", true);
const dbName = "proDB";

const userSchema = new mongoose.Schema({
  title: String,
  filepath: String,
});
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

app.get("/", function (req, res) {
  User.find({}, function (err, foundItems) {
    console.log(foundItems.title);
  });
  res.render("index");
});
app.post("/upload", function (req, res, err) {
  const user = User({
    title: req.body.podcastTitle,
    filepath: req.body.filePath,
  });
  user.save();

  res.redirect("/admin-login");
});

索引.ejs

<% newListItems.forEach(function(item){ %>
       <div class="video-div">
          <p><%=item.title%></p>
       </div>
<% }) %>

您需要將要顯示的變量傳遞給res.render方法:

res.render(view [, locals] [, callback])

渲染視圖並將渲染的 HTML 字符串發送到客戶端。 可選參數:

locals,一個 object,其屬性定義視圖的局部變量。

回調,一個回調 function。 如果提供,該方法將返回可能的錯誤和呈現的字符串,但不執行自動響應。 發生錯誤時,該方法在內部調用 next(err)。

要使您的代碼正常工作,請將渲染 function 調用移動到查詢回調中,並將找到的用戶傳遞給它:

app.get("/", function (req, res) {
  User.find({}, function (err, foundItems) {
    console.log(foundItems.title);
    
    res.render("index", {newListItems: foundItems});
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM