Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform a find query in Mongoose?

i have a collection of Ebooks data in mongodb like

{ 
    "_id" : ObjectId("58b56fe19585b10cd42981d8"), 
    "cover_path" : "D:\\Ebooks\\uploads\\ebooks\\cover\\1488285665748-img1-700x400.jpg", 
    "path" : "D:\\Ebooks\\uploads\\ebooks\\pdf\\1488285665257-Webservices Natraz.pdf", 
    "description" : "ebook", 
    "title" : "book name", 
    "tag" : [
        "Hindi", 
        "Other"
    ], 
    "__v" : NumberInt(0)
}

Now i want to search something if keyword is little bit match from "title:" then show all related books object.

My Mongoose schema is :-

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var EbookSchema   = new Schema({
    title: {type:String},
    description: {type:String},
    path: {type:String,required:true},
    cover_path: {type:String,required:true},
    tag: [{ type: String }]

});
module.exports = mongoose.model('Ebook', EbookSchema);

I try :-

app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
    Ebook.find(title:'search',function(err, ebooks) {
            if (err)
                res.send(err);

            res.json(ebooks);
        });
    });

but i found null how can i do ? i only want when i search a little-bit keyword i found all related object .

like image 930
Sayed Tauseef Haider Naqvi Avatar asked Mar 01 '17 20:03

Sayed Tauseef Haider Naqvi


1 Answers

Try wrapping your query in curlies, Mongoose expects an object as the query.

app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
    Ebook.find({title: search_key})
       .then(ebooks => res.json(ebooks))
       .catch(err => res.status(404).json({ success: false }));
    });
like image 154
Andy Macleod Avatar answered Sep 30 '22 19:09

Andy Macleod