Linked Questions

Popular Questions

Simple mock library app, there is a mongodb database that has 2 collections, one for books and one for authors.
In the books collection there is a field for the book title. The current field type is set to 'String'.

This will allow for a title with spaces in it to be saved without a problem. eg: "The Illiad"

Confirmed, I can retrieve a single word title document. eg: "Space"

When I use my (react) front end and search for a book by title, I will not get a return document if searching for a book with a title that has more than one word, this must be because of the spaces in the search query.

The 'input search value' is being taken and used as the query parameter.

What would be the proper way to handle this to be able to find the a title even with spaces?

Here is the search components relative code:

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

And here is the backend route controller logic:

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

And here is the schema/model for good measure:

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

Thanks

Related Questions