我有mongodb中的Ebooks数据集合,如
{
"_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)
}
现在我想搜索一下,如果关键字与"title:"
有点匹配,则显示所有相关图书对象。
我的Mongoose架构是: -
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);
我尝试: -
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);
});
});
但我发现null怎么办?我只想在搜索一点点关键字时找到所有相关对象。
答案 0 :(得分:6)
尝试用curlies包装你的查询,Mongoose期望一个对象作为查询。
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 }));
});