【问题标题】:Get data from mongoDB collection to ejs从 mongoDB 集合中获取数据到 ejs
【发布时间】:2021-05-21 19:52:46
【问题描述】:

我正在学习如何使用 MongoDB 地图集。我将数据库与我的节点应用程序连接起来,并且还可以向其中添加数据。我面临的唯一问题是 ejs。我无法从我的集合中检索我的文件路径和标题,即使我能够记录我的集合中的所有数据,但我被困在如何从我的集合中获取标题和文件路径并使用我前面的数据-结尾。这是我的代码:

app.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");
});

index.ejs

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

【问题讨论】:

    标签: node.js mongodb express mongoose ejs


    【解决方案1】:

    您需要将要显示的变量传递给res.render 方法:

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

    渲染一个视图并将渲染后的 HTML 字符串发送给客户端。可选参数:

    locals,一个对象,其属性定义视图的局部变量。

    callback,回调函数。如果提供,该方法将返回可能的错误和呈现的字符串,但不执行自动响应。发生错误时,该方法在内部调用 next(err)。

    要使您的代码正常工作,请将渲染函数调用移到查询回调中,并将找到的用户传递给它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-15
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 2016-05-19
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多