当涉及到“空格”时,保存并查询mongodb。 (MERN堆栈,猫鼬)

时间:2019-02-11 20:27:41

标签: javascript mongodb mongoose

一个简单的模拟库应用程序,有一个mongodb数据库,其中包含2个收藏集,一个用于书籍,一个用于作者。
在书籍集中,有一个书名字段。 当前字段类型设置为“字符串”。

这样可以毫无问题地保存带有空格的标题。  例如:“ The Illiad”

确认,我可以检索一个单词标题文档。  例如:“太空”

使用(反应性)前端按标题搜索书时,如果搜索标题多于一个单词的书,则不会得到退货文档,这一定是由于中的空格搜索查询。

正在使用“输入搜索值”并将其用作查询参数。

处理这个问题的正确方法是什么,即使有空格也能找到标题?

以下是搜索组件的相对代码:

    handleSubmit = e => {
        let queryParam = this.state.searchValue;
        e.preventDefault();

        if(this.state.selectedOption === 'one') {
            Axios.get(`/books/${queryParam}`)
                .then(data => console.log(data.data))
                .catch(err => console.log(err))
            console.log(queryParam)
            console.log(this.state.selectedOption)
        } else if (this.state.selectedOption === 'two') {
            Axios.get(`/authors/${queryParam}`)
                .then(data => console.log(data.data))
                .catch(err => console.log(err))
            console.log(queryParam)
            console.log(this.state.selectedOption)
        }
    }

这是后端路由控制器逻辑:

// Get one book by title
exports.author_name = (req, res) => {
    Book.findOne({name: req.params.name})
        .then(doc => res.json(doc))
        .catch(err => console.log(err))
};

这是很好的方案/模型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BookSchema = new Schema({
    title: {
        type: String,
        required: true,
        lowercase: true
    },
    author: {
        type: String,
        required: true,
        lowercase: true
    },
    genre: {
        type: String,
        required: true,
        lowercase: true
    },
    pages: {
        type: Number
    },
    available: {
        type: Boolean,
        default: true
    },
    book_id: {
        type: Number,
        required: true
    }
});

module.exports = Book = mongoose.model('book', BookSchema);

谢谢

0 个答案:

没有答案