如何在expressjs和mongodb中创建搜索端点

时间:2019-07-31 11:33:05

标签: node.js mongodb api express mongoose

我正在尝试在我的其余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;
  

controller / 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);

2 个答案:

答案 0 :(得分:0)

您错过了这个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
     });
  });
};

答案 1 :(得分:0)

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

在Post Query中,您只能从query对象获取req,而不能从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.find({ $text: { $search: req.query.q } }) // Post.find({ $text: { $search: 'alex' } })

我希望此帮助和其他复杂查询I found this helpful