简体   繁体   English

如何搜索文本并打印相应的ID

[英]How to search for text and print respective ids

I am making a website in which there is a function which will take an input and search for the text on mongoDB. 我正在制作一个网站,其中有一个功能将接受输入并在mongoDB上搜索文本。 I want to print all the user names which have such texts in their data. 我要打印所有在其数据中包含此类文本的用户名。

I have tried looking up the official documentation and making changes to find a solution but nothing has helped so far. 我尝试查找官方文档并进行更改以找到解决方案,但到目前为止没有任何帮助。

// Search
router.post('/search', ensureAuthenticated, (req, res) => {
    const { name } = req.body;
    console.log(name);
    //I want to get the username and that specific data printed which is inside an array called books
    const Results = User.find( { $text: { $search: name } } );
    console.log(Results);
    res.redirect('borrow');
});

The actual result is nothing as I am not able to progress any further. 实际结果无济于事,因为我无法进一步发展。 The expected result is to get an multi-dimensional array which will have the user and the corresponding book. 预期的结果是获得一个多维数组,该数组将包含用户和相应的书。

For example if I have 2 people User 1 has books: Harry Potter Angels and Demons Shy Harry 例如,如果我有2个人,则用户1有书:哈利·波特天使与魔鬼害羞的哈里

User 2 has books: Harry Bad 用户2拥有书籍:Harry Bad

If I search for harry then I want to store all the users which harry along with the books. 如果我搜索哈利,那么我想将所有哈利用户与书籍一起存储。

You need to make some changes in code. 您需要对代码进行一些更改。 So use code below. 因此,请使用下面的代码。

router.post('/search', ensureAuthenticated, async(req, res) => {
    const { name } = req.body;
    console.log(name);
    //I want to get the username and that specific data printed which is inside an array called books
    const Results = await User.find( { $text: { $search: name } } );
    console.log(Results);
    res.redirect('borrow');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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