简体   繁体   中英

Get data from mongoDB collection to ejs

I was learning how to use MongoDB atlas. I connected the database with my node app and I am also able to add data to it. The only problem that I am facing is with ejs. I am not able to retrieve my filePath and title from my collection, even though I was able to log all of the data in my collection but I am stuck at how can I get title and filePath from my collection and use the data on my front-end. Here is my code:

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>
<% }) %>

You need to pass the variables you want to display to the res.render method:

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

Renders a view and sends the rendered HTML string to the client. Optional parameters:

locals, an object whose properties define local variables for the view.

callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

To make your code work, move the render function call inside the query callback, and pass the found users to it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM