【问题标题】:mongo db text search on an object对象上的mongodb文本搜索
【发布时间】:2021-06-30 14:44:02
【问题描述】:

我正在下面我的模型中的location 对象上对我的 API 设置 mongo db 测试搜索。 尝试在数据库中设置文本搜索时出现错误,如下所示。请问可能是什么问题?

const mongoose = require('mongoose')

const placeSchema = new mongoose.Schema({
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    location: {
        country: {
            type: String,
            required: true,
        },
        street: {
            type: String,
            required: true,
        },
        city: {
            type: String,
            required: true,
        },
        state: {
            type: String,
            required: true,
        },
        zip: {
            type: String,
            required: true,
        }
    },
    price: {
        currency: {
            type: String,
            required: true
        },
        amount: {
            type: Number,
            required: true
        }
    }
    img: {
        type: Boolean,
        required: false,
        default: false
    },
    phone: {
        code: {
            type: String,
            required: true
        },
        number: {
            type: String,
            required: true,
        }
    },
})

placeSchema.index({ location.country: 'text', location.street: 'text', location.city: 'text', location.state: 'text', location.zip: 'text' })


const Place = mongoose.model('Place', placeSchema)

module.exports = Place

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-atlas


    【解决方案1】:

    你应该试试这个辅助函数。

    您可以将搜索词作为第一个参数传递,将搜索字段数组作为第二个参数传递。

    module.exports.searchHelper = function (searchWord, fields) {
        let orArr = [];
        let search = searchFiled.split(" ");
        fields.forEach((element1) => {
            search.forEach((element) => {
                orArr.push({ [element1]: { $regex: new RegExp(element, "i") } });
            });
        });
        return { $match: { $or: orArr } };
    };
    

    现在你必须在管道中聚合它:

    let fieldsArray = ['location.country','location.city','location.state'] //as per your need
    
    let pipeline = [];
    
    pipeline.push(searchHelper(searchWord, fieldsArray));
    
    const results = await Place.aggregate(pipeline);
    

    【讨论】:

    • 兄弟,我会试试这个,但似乎使用这个解决方案我将无法使用 document.find 并传递我除了搜索之外还想使用的其他过滤器?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2016-05-28
    • 2012-03-26
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2018-09-27
    相关资源
    最近更新 更多