我正在尝试在我的其余API中创建搜索端点。在其中查询具有用户提供的帖子标题的帖子。我尝试了一段时间,但仍然无法做到。任何人,请帮助我做到这一点。
我尝试的方式无效。在postman
中测试搜索端点时,它总是给我一个空数组。这些是我的密码。
帖子/模型
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.post('/posts/search', postController.search);
答案 0 :(得分:0)
您错过了这个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和$ search不应为字符串
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
});
});
};
答案 1 :(得分:0)
您已经完成了工作的重要部分,这只是查询中的一个错误,即使没有postSchema.index({'$**': 'text'});
也应该可以工作。
在Post Query中,您只能从query
对象获取req
,而不能从body
获取。
差错
Post.find({ $text: { $search: req.body.query } })
更正
Post.find({ $text: { $search: req.query } }) // Post.find({ $text: { $search: {} } })
并注意:
在我上面的更正中,显示req.query
是一个对象。
localhost:4000/api/v1/search?q=alex
然后期望您的req.query
是{ q: 'alex' }
。因此要重写后查询。会
Post.find({ $text: { $search: req.query.q } }) // Post.find({ $text: { $search: 'alex' } })
我希望此帮助和其他复杂查询I found this helpful。