猫鼬搜索返回错误的结果

时间:2020-01-05 00:35:34

标签: javascript node.js mongoose

我想在“全名”字段中找到所有包含“ user1”的文档。 但是它只返回“ user1”(我的数据库中存在user10,user11,user123,user111)

---------------已解决-----------------------

router.get('', async (req, res) => { 
    const search = req.query.search !=null ? req.query.search : "";
    const page = req.query.page !=null ? req.query.page : 1;
    const limit = req.query.limit !=null ? req.query.limit : 4;
    try {
        User.paginate({$text: {$search: search}}, {page: page, limit: limit, customLabels: myCustomLabels}, function (err, result) {
                console.log(result)
                res.json(result)
        }
        );
    }
    catch(e){
        console.log('Something went wrong:  ', e)
    }
})

型号:

const {Schema, model, Types} = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');

const schema = new Schema ({
    fullname: {type: String, required: true},
    email: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    followed: {type: Boolean},
    status: {type: String},
    city: {type: String},
    country: {type: String}
});
schema.plugin(mongoosePaginate);

schema.index({fullname: 'text'});

module.exports = model('User', schema);

我的要求: http://localhost:8000/api/user?search=user1

1 个答案:

答案 0 :(得分:0)

使用正则表达式功能

{ name: { $regex: searchText, $options: '-i' } }