【问题标题】:How to create search endpoint in expressjs and mongodb如何在 expressjs 和 mongodb 中创建搜索端点
【发布时间】:2019-12-08 21:59:22
【问题描述】:

我正在尝试在我的 REST API 中创建搜索端点。它使用用户提供的帖子标题查询帖子。我正在尝试一段时间,但仍然无法做到。任何人,请帮我做这个。

我尝试的方法不起作用。在postman 中测试搜索端点时,它总是给我一个空数组。这些是我的代码。

帖子/模型

import mongoose from 'mongoose';

const {Schema}  = mongoose;
mongoose.Promise = global.Promise;
const postSchema = new Schema({
    title: {type: String, required: true},
    link: String,
    text: String,
    isDeleted: {type: Boolean, default: false},
    createdAt: {type:Date,default: Date.now},
    _creator: {type: Schema.ObjectId, ref: 'User'},
    _comments: [{type: Schema.ObjectId, ref: 'Comments' }]
});

const Post = mongoose.model('Post', postSchema);
export default Post;

控制器/postscontroller.js

postController.search = (req, res) => {
    db.Post.find({'$text': {'$search': req.body.query}})
        .then(result => {
            console.log(result);
            res.status(200).json({
                result
            })
        })
        .catch(err => {
            res.status(500).json({
                error: err
            })
    })
};

路线

routes.post('/posts/search', postController.search);

【问题讨论】:

  • 您是否在收藏中添加了 textindex 以执行文本搜索?
  • @SachinVishwakarma 不,我不知道它是什么以及如何做到这一点。

标签: node.js mongodb api express mongoose


【解决方案1】:
//you can searching data from db is very easy you can use only create condition objext and pass to the find() 
var text = req.body.text;
var search_conditionObject = {
    name: { $regex: text ,$options:'i'}
};
const search_data = db.find(search_conditionObject )
    .then(data => {
        console.log(data);
        res.status(200).json({
            sreach_data
        }) 
    })

    .catch(err => {
        res.status(500).json({
            error: err
        })
    })

【讨论】:

  • Stack Overflow 不仅仅是为了解决眼前的问题,也是为了帮助未来的读者找到类似问题的解决方案,这需要了解底层代码。这对于我们社区的初学者和不熟悉语法的成员来说尤其重要。鉴于此,您能否编辑您的答案以包括对您正在做什么以及为什么您认为这是最佳方法的解释? 为什么您的答案比其他答案有所改进?
【解决方案2】:

您已经完成了工作的重要部分,这只是您的查询中的一个错误,即使没有postSchema.index({'$**': 'text'}); 它也应该可以工作。

在您的 Post Query 中,您只能从 req 对象中获取您的 query,而不能从 body 中获取。

错误

Post.find({ $text: { $search: req.body.query } })

修正

Post.find({ $text: { $search: req.query } }) // Post.find({ $text: { $search: {} } })

注意:

在我上面的更正中,req.query 是一个对象。

简而言之,您的查询将始终是一个对象。如果您的网址是localhost:4000/api/v1/search?q=alex 然后期望您的req.query{ q: 'alex' }。所以要重新写post查询。会的

Post.find({ $text: { $search: req.query.q } }) // Post.find({ $text: { $search: 'alex' } })

我希望这对I found this helpful的其他复杂查询有所帮助。

【讨论】:

    【解决方案3】:

    你错过了这个 postSchema.index:

    import mongoose from 'mongoose';
    
    const {Schema}  = mongoose;
    mongoose.Promise = global.Promise;
    const postSchema = new Schema({
    title: {type: String, required: true},
    link: String,
    text: String,
    isDeleted: {type: Boolean, default: false},
    createdAt: {type:Date,default: Date.now},
    _creator: {type: Schema.ObjectId, ref: 'User'},
    _comments: [{type: Schema.ObjectId, ref: 'Comments' }]
    });
    
    //you missed this line, this will search in all fields
    postSchema.index({'$**': 'text'});
    // or if you need to search in specific field then replace it by:
    //postSchema.index({text: 'text'});
    
    const Post = mongoose.model('Post', postSchema);
    export default Post;
    

    $text 和 $search 不应该是字符串

    postController.search = (req, res) => {
      Post.find({$text: {$search: req.body.query}})
        .then(result => {
            console.log(result);
            res.status(200).json({
                result
            })
        })
        .catch(err => {
            res.status(500).json({
                error: err
         });
      });
    };
    

    【讨论】:

    • 这不起作用。我仍然得到一个空数组。
    • 在 Post.find 之前添加 console.log(req.body.query) 后,我在日志中得到了这个 { query: 'google post' } 我有一个标题为 google post 的帖子。但是在测试这个端点时它仍然返回一个空数组。
    猜你喜欢
    • 2021-12-06
    • 2017-02-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多