I want to implement whole search feature in Mongodb collection using Nodejs. What should I pass to SaleModel.find()
so given value search in whole collection?
Here is what I have try so for but it only search product_name and I want to search sale_amount, sale_person, department_name too.
How I can do this?
SaleModel.find({'product_name': 'searched value'});
Schema:
var saleSchema = mongoose.Schema({
product_name:{ type:String, required:true},
sale_amount:{ type:Number, required:true },
sale_date:{ type:Date, default:Date() },
sale_person:{ type:String, required:true },
department:{ type:mongoose.Schema.Types.ObjectId, ref:'department' },
});
module.exports = mongoose.model('sale', saleSchema);
I would highly write more cleaner, below sample uses async.parallel
, Promise and Mongoose.Query
function list(req) {
// promise or callback works as well
return new Promise(function(resolve, reject){
// npm install async --save
var async = require('async');
// some validation can be applied
var page = {
skip: req.query.start || 1,
limit: req.query.length || 25,
text: req.query.search || '' // <== this is new property!
};
// reuse Mongoose.Query with search by regex
var Query = Models.SaleModel.find({
product_name: new RegExp(page.text, "i")
});
// run without waiting until the previous function has completed
async.parallel([
function(){
Query.count(callback); // <== count
},
function(){
Query.skip(page.skip).limit(page.limit).exec('find', callback); // <== items
// or the below one should also work, just don't remember
// Query.skip(page.skip).limit(page.limit).exec(callback);
}
]), function(err, results){
if(err){
reject(err);
} else {
resolve({
count: results[0],
data: results[1]
});
}
});
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.