0 votes
1 view
in Web Technology by (47.8k points)

I have a collection of Ebooks data in mongodb like

"_id" : ObjectId("58b56fe19585b10cd42981d8"), 

"cover_path" : 


x400.jpg", "path" : 


s 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 :-


var search_key = req.param('search'); 

Ebook.find(title:'search',function(err, ebooks) { 

if (err) res.send(err); 




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

2 Answers

0 votes
by (107k points)

To perform a find query in Mongoose you should try wrapping your query in curlies, Mongoose expects an object as the query.


var search_key = req.param('search'); 

Ebook.find({title: search_key}) 

.then(ebooks => res.json(ebooks)) 

.catch(err => res.status(404).json({ success: fals})); 


0 votes
by (90.3k points)
edited by

Basically model.find() function helps in returning an instance of Mongoose's Query class. The 'Query' class expresses a raw CRUD(Create, Read, Update, Delete) operations that you may pass to MongoDB. Model.find() instantiates a query for you, you don't have to instantiate directly:

const q1 = Customer.find();

q1 instanceof mongoose.Query; // true

const document1 = await q1; // Get the documents

Then you can simply wrap your query in the curlies as discussed in the above solution. 

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
+1 vote
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !