Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with:

 <form id="contact-form" method="POST" action="/search">
            <label for="company">Phone company</label>
            <input type="text" name="company" value="">
            <br>
            <label for="modelname">Model name</label>
            <input type="text" name="modelname" value="">
            <br>
            <label for="numbername">Model number</label>
            <input type="text" name="numbername" value="">
            <br>
            <input type="submit" value="Search">
        </form>

Defining the phone schema in JavaScript:

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

const phoneSchema = new Schema({
    company: String,
    modelname: String,
    numbername: String,
    picture: String,
    price: String,
});

const Phone = mongoose.model('phone', phoneSchema);

module.exports = Phone;

Example of a phone entry in the database:

{
    "_id" : ObjectId("5b155a66aced9b079c276ba0"),
    "company" : "Samsung",
    "modelname" : "Galaxy",
    "numbername" : "S5",
    "picture" : "https://drop.ndtv.com/TECH/product_database/images/2252014124325AM_635_samsung_galaxy_s5.jpeg",
    "price" : "12500P",
    "__v" : 0
}

Handling POST requests:

    app.post('/search', urlencodedParser, function(req, res){
    console.log(req.body);
    Phone.findOne({company: req.body.company, modelname: req.body.modelname, numbername: req.body.numbername}).then(function(){
        .......

})});

If the company, model name, and model number in the form match those in the database, then render the page with all the relevant information (company + picture + price). How can we compare the form data with the data in the database effectively?

Answer №1

It appears that you are attempting to retrieve database information and pass it back to an HTML page. This situation is similar to the question discussed here: How do I serve partially dynamic HTML pages with Express? If you need to apply any filters, you can achieve this using queries. More information on this topic can be found here: How to get GET (query string) variables in Express.js on Node.js? If you are looking for a workaround, you can send an XMLHttpRequest to your server and parse the response.

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var data = JSON.parse(xhttp.responseText);
        console.log(data)
    }
}
xhttp.open("POST", '/search', true);
xhttp.send();
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

Is it possible to selectively render a page or component in Next.js 13 based on the request method?

Is there a way to conditionally render a page based on the request method in Nextjs 13? For example, when registering a user, can we show a signup form on a get request and display results on a post request? With all components now being server components ...

What are the steps to releasing and utilizing a Node package in Laravel 5?

Recently, I've started integrating Vuejs into my existing laravel application. Although it's a new experience for me, I'm excited to learn more about it. One feature that caught my eye is this component: A multiselect with search-autocomple ...

Is there a method for uploading and viewing files from a server using the MERN stack?

Looking to create a functionality for users to upload various file types such as documents, presentations, and text files, save them to a database, and then view them from the server. Are there any recommended frameworks or npm modules to help with this ...

What is the reason for $http.get not requiring a return value?

I am currently developing an angular application and I have a controller that interacts with a service. The controller sends a URL to the service, which then makes a GET request to that URL and receives JSON data in return. Within this JSON data is a URI f ...

Trouble with the filter function in the component array

I am facing an issue with creating and deleting multiple components. I have successfully created the components, but for some reason, I am unable to delete them when I click on the "delete" button. state = { data: '', todoCard: [], id ...

The implementation of CORS headers does not appear to function properly across Chrome, Firefox, and mobile browsers

I encountered an issue while trying to consume a third party's response. The functionality works correctly in Internet Explorer, but fails in Chrome, Firefox, and on my mobile browser. Despite searching online and testing various codes, I continue to ...

Is it recommended to utilize CDN in Vue.js for optimal performance?

Currently facing a version compatibility issue between leaflet and leaflet-draw in my vuejs project. In light of this, I am seeking alternative solutions for map function editing such as adding polylines, copy and paste functions, and more. While I did com ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Traverse a collection of nested objects containing arrays as their values

Consider the following object: { "apples": [ "one", "two" ], "oranges": [ "three", "four" ] } If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below? for (var ...

Ensuring that the image perfectly fills the entire screen on an iPhone X using React Native

Looking for a solution to make my image fit the entire screen on the iPhone X simulator. I've tried adjusting the imageContainer width to "100%" and the container that encompasses everything, but haven't had any luck. Would appreciate any suggest ...

Loop through each instance of a data record in a JSON document using Vue's v-for directive

I am currently working on a project that involves extracting data from a website that monitors traffic jams and maintenance work. My goal is to specifically retrieve information about traffic jams and display them individually. The code I am using utilize ...

The current version of JavaScript does not have support for string templates

Attempting to utilize ES6 String Templates in a Node.js (version 5.7.0) application, but encountering issues. Webstorm is alerting me that The current Javascript version does not support string templates I am positive I have successfully used string te ...

Retrieve just the message from the error callback in Node

Beginner in the world of node. I'm interested to find out if node has a built-in feature that allows for easy extraction of error messages from an error object. conn.query(sql, params, function (err, rows) { if (err) { ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

The process of incorporating user properties into the output of a Service Bus topic from a Javascript Azure Function

I'm currently developing a TypeScript Azure Function that utilizes an Azure Service Bus topic as its output. Although I am able to send messages successfully, I have encountered difficulties in setting custom metadata properties for the message. In m ...

Error: Unable to access the 'version' property of null

Having trouble installing any software on my computer, I've attempted various solutions suggested here but none have been successful. $ npm install axios npm ERR! Cannot read property '**version**' of null npm ERR! A complete log of this ru ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

The Distinction Between "Q" and "q" in AngularJS and RequireJS

Currently, my project involves developing a single page application using AngularJS, Breeze, and RequireJS. While trying to configure AMD with requirejs to integrate Angular and Breeze, I ran into an issue related to Breeze's dependency on "q". Intere ...