Have you heard of MEVN? It involves using MongoDB for your database needs. To start off, it's essential to create an API search endpoint that functions like this:
//search.js
import User from "../models/user";
export default async function(req, res) {
let query = req.body.query;
if (!query) {
return res.status(200).json([]);
}
const users = await User.aggregate([
{
$searchBeta: {
search: {
query,
path: ["name", "surname"],
phrase: {
prefix: true
}
}
}
}
]);
return res.status(200).json(users);
}
Let me break down the aggregation pipeline for you. Initially, you need to import your mongoose schema (if you're using mongoose). The key here is the $searchBeta
stage. This stage conducts a full-text search on designated fields. In my scenario, I'm searching for users based on their names and surnames, looking for any relevant matches. The setting is such that the phrase
parameter is set to prefix=true
, enabling instant results with just one character input.
The resulting Array returned by the API endpoint will contain documents matching the criteria, sorted by a searchScore
.
In your frontend implementation, consider something along these lines:
<template>
<div class="searchbox">
<input
@keyup="search"
placeholder="Search..."
type="text"
v-model="query"
/>
<div
class="result"
v-for="result in matchArray"
:key="result._id"
>
<div class="account_box">
<i class="far fa-user"></i>
</div>
<p>{{ result.name + " " + result.surname }}</p>
</div>
</div>
</template>
<script>
export default {
data(){
return {
query: "",
matchArray: []
}
},
methods: {
axios.post("/api/search", {
query: this.query:
})
.then(res => {
matchArray = res.data;
});
}
}
</script>