0

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>[email protected]/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> <% }) %> 

1 Answer 1

1

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}); }); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.