【问题标题】:mongodb full $text search returns duplicate items when sorting and filteringmongodb full $text search在排序和过滤时返回重复项
【发布时间】:2021-07-28 23:53:36
【问题描述】:

我在我的 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" })
    }
})

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您可以尝试使用 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;
    

    示例获取所有用户方法,注意排序可以传入选项。您可以随意使用 options 对象

     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});
         }
      });
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2013-02-20
      • 2011-02-22
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多