创建搜索页面

时间:2019-07-04 04:50:46

标签: node.js mongodb

我想在nodejs中创建一个搜索页面。在我的代码中,我从另一个页面获取输入并将结果呈现到单独的页面:

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

这是我的“ searchResults”页面代码

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

我目前得到countMoviesSearch,但在searchmovies.name中却未定义,我的所有输入变量都相同。

1 个答案:

答案 0 :(得分:1)

find()方法返回一个Cursor对象。您需要调用toArray()来获取文档数组。由于有了数组,因此可以访问.length属性以获取匹配的电影,以避免再次运行同一查询

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