As the title says I am trying to add documents from my mongodb into an array in the controller. The following code is what my controller looks like:
var express = require('express');
var router = express.Router();
var moviesModel = require("../models/movies");
/* GET /movies/ listing. */
router.get('/', function(req, res, next) {
moviesModel.find({}).where('Price').gt(10000).exec(function(err,movies){
if(err) throw err;
console.log(movies);
});
});
module.exports = router;
The code above console logs 5 docs. Those are the docs I am trying to add to an array. My goal is to insert the docs into an array then iterate through each element and display it through the view. I dont konw if this is possible. If you have suggestions as to how I should approach this please let me know. Any help would be appreciated. Thanks!
First, you have to pass your movies
to the view through the second argument of res.render
method:
var express = require('express');
var router = express.Router();
var moviesModel = require("../models/movies");
/* GET /movies/ listing. */
router.get('/', function(req, res, next) {
moviesModel.find({}).where('Price').gt(10000).exec(function(err,movies){
if(err) throw err;
console.log(movies);
res.render('layout.ejs', {movies: movies});
});
});
module.exports = router;
and the second step is looping through movies
in the view and output in the format you desire like the following:
layout.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<title>My movies</title>
</head>
<body>
<ul>
<% for(var i=0; i<movies.length; i++) {%>
<li><%= movies[i] %></li>
<% } %>
</ul>
</body>
</html>
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.