javascript - mongodb full $text search在排序和过滤时返回重复项
问题描述
我在我的 API 中使用全文搜索并使用分数进行排序。问题是在搜索后我通常会不止一次地得到一个项目,这不是我所期望的行为。请问,我该如何纠正这个?
这是我的路由器的设计方式
router.get('/place', async (req, res) => {
const match = {
deactivated: false,
}
const sort = {}
if (req.query.search) {
match.$text = {$search: req.query.search}
sort.score = {$meta: "textScore"}
}
const noOnPage = parseInt(req.query.limit) || 20
const pageNo = (parseInt(req.query.page)-1)*parseInt(req.query.limit) || 0
const endIndex = parseInt(req.query.page)*parseInt(req.query.limit)
const next = parseInt(req.query.page)+1
const previous = parseInt(req.query.page)-1
try {
const count = await Place.find(match).countDocuments().exec()
const place = await Place.find(match, sort)
.limit(noOnPage)
.skip(pageNo)
.sort(sort)
const result = {}
// Shows the search result count
result.resultCount = count
// Shows the previous page number
if (parseInt(req.query.page)!=1) {
result.previous = previous
}
// Shows the next page number
if (endIndex < count) {
result.next = next
}
// assigns the search results to variable names results
result.results = place
res.status(200).send(result)
} catch (e) {
res.status(400).send({ "message": "something went wrong please reload page" })
}
})
解决方案
您可以尝试使用 mongoose 分页模块。以下是您需要进行的简单更改。
示例用户模型:
import {model, Schema} from 'mongoose';
const mongoosePaginate = require('mongoose-paginate-v2');
const userSchema = new Schema({
firstname: { type: String,trim:true},
lastname: { type: String,trim:true},
isconfirmed:{type:Boolean,default:false},
},
{timestamps:true});
userSchema.plugin(mongoosePaginate);
const appUsers:any = model('appusers', userSchema);
export default appUsers;
示例获取所有用户方法,注意排序可以在选项中传递。您可以随意使用选项对象
getAllUsers(req:Request,res:Response){
const options = {page: req.body.page?req.body.page:1,limit: 10,collation:
{locale: 'en'},sort:{createdAt:-1},select: {_id:1,firstname:1,lastname:1}};
appUsers.paginate({}, options, function(err:any, result:any) {
if(err){
res.status(500).json({status:false,msg:"Failed to fetch All
users",err:err});
}else{
res.status(200).json({status:true,msg:"List populated",data:result});
}
});
}
推荐阅读
- c# - 返回、示例等 XML 文档注释以供在 IDE 中使用
- python - 如何创建一个由 2 个不同列表元素组合而成的新列表而不重复?
- angular - ionic 4 native http在html中获取空数据
- python - 有没有办法在python中强制互斥函数参数?
- java - 来自 Hibernate 包的 CascadeType 的 ConstraintViolationException
- regex - 正则表达式可以处理嵌套操作吗?
- python - Pytest 不使用 pytest 命令收集测试
- docker - Docker:等待IP超时
- java - FirebaseAuth.getInstance().getUid() - 它是如何工作的?
- python - 如何从文件中打印具有最大数字的字符串