today I was working on a project that I've, it's made with node.js, express and it uses mongoDB; there I have an input with a search button to look up for users that their name matches with the data input.
I was wondering if there is a way to search just a letter to see every user which they name starts with that particular letter.
Right now I can just search for users that their full name its exactly the same as what the user has written, like if the user name is John, you have to write John or it won't find any match at all.
What I want to achieve, is that if the user puts "jo" as the input, I want to show every user that has "jo" on it's name.
If somebody could clarify this for me it would be really helpful!.
index.js :
const path = require("path");
const MongoClient = require("mongodb").MongoClient;
const bodyParser = require("body-parser");
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const express = require("express");
const app = express();
require("dotenv").config();
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true
})
);
const port = 8080;
app.listen(port, () => {
console.log(`Server Runing On Port ${port}`);
});
const mongoKey = process.env.MONGOKEY;
const mongoUsr = process.env.MONGOUSR;
const mongoCluster = process.env.MONGOCLUSTER;
const uri = `mongodb+srv://${mongoUsr}:${mongoKey}@${mongoCluster}`;
const client = new MongoClient(uri, { useNewUrlParser: true });
app.post("/search", (req, res) => {
const user = req.body.userName;
client.connect((err, db) => {
if (err) {
console.log("cannot connect db" + err);
return;
}
console.log("DataBase connection made successfully");
const options = {
sort: "userName"
};
const collection = db.db().collection("UserData");
collection.findOne({ userName: user }, options, (err, doc) => {
if (err) {
console.log("cannot make query" + err);
res.statusMessage = "Cannot Make Query";
res.statusCode = 400;
return;
}
let document = doc.userName;
console.log(document);
});
});
});
index.html form:
<form
class="contentForm"
action="/search"
method="POST"
enctype="application/x-www-form-urlencoded"
>
<h3>Search for Any user here:</h3>
<div class="searchBox">
<input type="text" class="searchInput" name="userName" />
<button type="submit" class="searchButton" />
</div>
</form>
MongoDb document example:
{"_id":{"$oid":"5e2201a99162aa0344ed4261"},
"userName":"John",
"email":"example@example.io",
"age":"23",
"password":"a01fbfc81d314dfa24329d4197e52f24e6d4116d4a205c6d09edf4dd3809943554e44d02e46a1c6368da2806ff8f0db5eb9beef7d0a0ea763625afab064783de",
"salt":"b787219f672e9d2fe76f1440055bca73"}
Thanks everyone!