Find Data in MongoDb Using Mongoose, Express JS Routes and $text Operator

Find Data in MongoDb Using Mongoose, Express JS Routes and $text Operator

Setup

First, install the necessary packages with:

npm install express cors mongoose

Code

Then, add dependencies to server.js create the database schema and the name of the collection, create an Express.js server, and connect to MongoDB:

const express = require('express')
const cors = require('cors') // we will use cores to enable cross origin domain requests.
const mongoose = require('mongoose')
const schema = mongoose.Schema

cont app =express()

const schemaName = new Schema({
 request: String,
 time: Number
},{
 collection: 'collectionName'
})
const Model = mongoose.model('Model', schemaName)
mongoose.connect('mongodb://localhost:27017/seacrhdb)

const port = 8080
app.list(port, () => {
console.log(`listening on port ${port}`)
})

Now and Express.js routes that we will use to query the data:

app.get('/find/:query', cores(), (req, res) => {
const query = req.params.query
Model.find({
        'request': query
    }, function(err, result) {
        if (err) throw err;
        if (result) {
            res.json(result)
        } else {
            res.send(JSON.stringify({
                error : 'Error'
            }))
        }
    })
})

Assume that the following documents are inthe collection inthe model:

{
        "_id" : ObjectId("578abe97522ad414b8eeb55a"),
        "request" : "JavaScript is Awesome",
        "time" : 1468710551
}
{
        "_id" : ObjectId("578abe9b522ad414b8eeb55b"),
        "request" : "JavaScript is Awesome",
        "time" : 1468710555
}
{
        "_id" : ObjectId("578abea0522ad414b8eeb55c"),
        "request" : "JavaScript is Awesome",
        "time" : 1468710560
}

And that the goal is to find and disolay all the documents containing only "Javascript" word under the "request" key.

To dot his, first creat a text index for "request" inthe collection. For this, add the following code to server.js:

schemaName.index({ request: 'text' });

And replace

 Model.find({
        'request': query
    }, function(err, result) {

with:

Model.find({
    $text: {
        $search: query
    }
}, function(err, result) {

Here, we are using $text and $search MongoDb operators for find all documents inc ollecion colleactionName which contains at least one word from the specified find query.

Usage

To use this to find data, go to the following URL in a browser:

http://localhost:8080/find/<query>

Expample:

http://localhost:8080/find/JavaScript

Outout:

[{
    _id: "578abe97522ad414b8eeb55a",
    request: "JavaScript is Awesome",
    time: 1468710551,
    __v: 0
},
{
    _id: "578abe9b522ad414b8eeb55b",
    request: "JavaScript is Awesome",
    time: 1468710555,
    __v: 0
},
{
    _id: "578abea0522ad414b8eeb55c",
    request: "JavaScript is Awesome",
    time: 1468710560,
    __v: 0
}]