Hasitha Chandula
Hasitha Chandula

Reputation: 435

Create search page

I would like to create a search page in nodejs. In my code, I take input from another page and render results to a separate page:

app.post("/searchProcess", async (req, res) => {
const keyWord = req.body.search;

const searchMovies = await Movies.find({
name: { $regex: new RegExp(keyWord) }
})
const countMoviesSearch = await Movies.find({
name: { $regex: new RegExp(keyWord) }
}).countDocuments();

console.log(countMoviesSearch);

// console.log(keyWord);
res.render("searchResults",{
  searchMovies: searchMovies,
  countMoviesSearch: countMoviesSearch
});
});

This is my "searchResults" page code

<h1>{{searchMovies.name}}</h1>
<h2>{{countMoviesSearch}}</h2>

I currently get countMoviesSearch, but in searchmovies.name I get undefined and my all input variables are same.

Upvotes: 1

Views: 109

Answers (1)

chakwok
chakwok

Reputation: 1040

The find() method returns a Cursor object. You need to call toArray() to get an array of documents. Since you have an array, you can access the .length property to get the matched movies, to avoid running the same query again

app.post("/searchProcess", async (req, res) => {
const keyWord = req.body.search;

const searchMovies = await Movies.find({
name: { $regex: new RegExp(keyWord) }
}).toArray()

const countMoviesSearch = searchMovies.length

console.log(countMoviesSearch);

// console.log(keyWord);
res.render("searchResults",{
  searchMovies: searchMovies,
  countMoviesSearch: countMoviesSearch
});
});

Upvotes: 1

Related Questions