0

I am trying to create search endpoint in my rest API. where it queries posts with the post title provided by users. I am trying this from a while but still, I am unable to make it. Anyone, please help me to make this.

The way I tried it doesn't work. It always gives me an empty array while testing search endpoint in postman. These are my codes.

posts/models

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

routes.post('/posts/search', postController.search);
aditya kumar
  • 2,905
  • 10
  • 39
  • 79

3 Answers3

0

you missid this 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 and $search shouldn't be a string

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
     });
  });
};
Nemer
  • 667
  • 1
  • 6
  • 10
  • This did not work. I am still getting an empty array. – aditya kumar Jul 31 '19 at 16:13
  • after adding `console.log(req.body.query)` before Post.find i get this in log `{ query: 'google post' } ` I have a post with title google post. but it is stilling returning an empty array while testing this endpoint. – aditya kumar Aug 02 '19 at 04:54
0

You've done the important part of your work, it's just a mistake in your query, even without postSchema.index({'$**': 'text'}); it should work.

In your Post Query, you can only get your query from req Object, not from body.

Mistake

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

Correction

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

And Note:

In my correction above shows a req.query is an object.

In a nutshell, Your query will always be an object. If your URL is localhost:4000/api/v1/search?q=alex then expect your req.query to be { q: 'alex' }. So to re-write the post query. It'll be

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

I hope this help and for other complex queries I found this helpful.

Akolade Adesanmi
  • 1,152
  • 11
  • 15
0
//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
        })
    })
  • 1
    Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?** Why is your answer an improvement over others? – zkoza Jan 08 '22 at 23:08