简体   繁体   中英

How to query mongodb for existing data on click from client side?

I am creating a express app where a user can search movies and add them to lists. If it's already added to list, I want to display 'Already added' instead of 'Added to list'. How can I query this from client side when the button is clicked.

server.js /search route

app.post('/search', (req, res) => {

    const id = req.body.id;
    const title = req.body.title;
    const rating = req.body.rating;
    const description = req.body.description;

    async function getMovie() {
            await AddedMovie.findOne({id: id}, (err1, succes) => {
            
            if (!succes) {
            
            const movie = AddedMovie({
                id: id,
                title: title,
                rating: rating,
                description: description
            })
    
            movie.save();
        }
        })
    }

    getMovie()
    .then(() => res.redirect('/search'))
    .catch(err => console.log(err));
})

Here I managed to save the movie to the list when the button is clicked, and it doesn't save when its already present in the db.

serach.ejs

const buttons = document.querySelectorAll('.addbtn');
    const ids = document.querySelectorAll('#hidden');
    const titles = document.querySelectorAll('.title');
    const ratings = document.querySelectorAll('.rating');
    const descriptions = document.querySelectorAll('.description')
    const success = document.querySelectorAll('.added');

    for (let i = 0; i < buttons.length; i ++) {
        buttons[i].addEventListener('click', () => {
            
            success[i].innerHTML = 'Successfully added to your list.';
            success[i].style.display = 'inline';
            setTimeout(() => {
                success[i].style.display = 'none';
                success[i].innerHTML = '';
            }, 4000);

            $.post('/search', {id: parseInt(ids[i].textContent), title: titles[i].textContent, rating: parseInt(ratings[i].textContent), description: descriptions[i].textContent })
        })
    }

The div displays 'added' when clicked, How can I display 'Already present' when its saved in database previously.

Update server.js to return the result of the find/add. In your case, if your findOne returns a successful result, return "Already Added" in your response. If findOne fails, add the movie and return "Successfully added to your list."

Update your client code to say "Adding to your list..." or something similar when the button is pressed and add a success handler to your post .

In your handler, you can grab the message that was sent from the server and display it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM